Friday, March 27, 2015

Send a notification on iPhone

First of all we need 3 things as mentioned:

1. Our iPhone's device token
2. .pem file for iPhone
3. Its passphrase.

Now use following code:

        $deviceToken = 'enter_your_device_token';
        $passphrase = 'enter_your_passphrase';
        $message = 'enter_your_notification_message';

        $badge = 1;
        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', 'path_to_pem_file.pem');
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

        // Open a connection to the APNS server
        $fp = stream_socket_client(
            'ssl://gateway.sandbox.push.apple.com:2195', $err,
            $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
        if (!$fp)
            exit("Failed to connect: $err $errstr" . PHP_EOL);
        echo 'Connected to APNS' . PHP_EOL;

        // Create the payload body
        $body['aps'] = array(
            'alert' => $message,
            'badge' => $badge,
            'sound' => 'newMessage.wav'
        );

        // Encode the payload as JSON
        $payload = json_encode($body);

        // Build the binary notification
        $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

        // Send it to the server
        $result = fwrite($fp, $msg, strlen($msg));

        if (!$result)
            echo 'Error, notification not sent' . PHP_EOL;
        else
            echo 'notification sent!' . PHP_EOL;

        // Close the connection to the server
        fclose($fp);


Thanks.

Friday, March 20, 2015

11 Rules All Programmers Should Live By

1: Technology is how you get to the solution, it is not THE solution
We can get really carried away with the latest JavaScript framework—ahem, Angular—IoC container, programming language or even operating system, but all of these things are not actually solutions to the problems we are trying to solve as programmers, instead they are simply tools that help us solve the problems.
We have to be very careful not to get too crazy about a particular technology that we happen to like or that happens to be oh so popular right now, lest we run the risk of thinking about every problem as a nail, just because we happen to be holding a shiny hammer we just learned about.

2: Clever is the enemy of clear

When writing code, we should strive to write code that is clear and easy to understand.
Code that clearly communicates its purpose is much more valuable than code that is obscure—no matter how clever it may be.
It’s not always true, but in general, clever is the enemy of clear.
It’s usually true that when we write code that is “clever,” that code isn’t particularly clear.
It’s important to remember this rule whenever we think we are doing something particularly clever.
Sometimes we write clever code that is also clear, but usually that is not the case.
If you’re interested in writing clean code I highly recommend you check out The Clean Coder: A Code of Conduct for Professional Programmers (Robert C. Martin)
code

3: Only write code if you absolutely have to

This one might seem a little contradictory, after all, isn’t our job as programmers to write code?
Well, yes and no.
Our jobs may involve writing code, but we should still strive to write as little of it as possible to solve the problem we are trying to solve.
This doesn’t mean we should make our code as compact as possible and name all our variables using single letters of the alphabet. What it does mean is that we should try to only write code that is actually necessary to implement the functionality that is required.
Often it is tempting to add all kinds of cool features to our code or to make our code “robust” and “flexible” so that it can handle all different kinds of situations. But, more often than not, when we try to guess about what features would be useful or we try to pave the road to solve for problems that we think might exist in the future, we are wrong.
This extra code may not add any value, but it can still do a lot of harm. The more code there is, the more chances for bugs and the more code that has to be maintained over time.
Good software engineers don’t write code unless it’s absolutely necessary.
Great software engineers delete as much code as possible.

4: Comments are mostly evil

“Every time you write a comment, you should grimace and feel the failure of your ability of expression.”
This doesn’t mean that you should never write comments, but for the most part they can be avoided and instead we can focus on doing a better job of naming things.
Comments should only really be written when it’s not possible to clearly communicate the intent of a variable or method by using a name. The comment then serves an actual purpose that could not be easily expressed in the code.
For example, a comment could tell us that this strange order in which some operation was occurring in the code was not a mistake, but was intentional because of a bug in the underlying operating system.
In general though, comments are not only evil because in many cases they are necessary, but also because they lie.
Comments don’t tend to get updated with the rest of the code and this results in the comments actually becoming dangerous, because they very well could steer you in a completely wrong direction.
Do we check every single comment against the code to make sure the code is actually doing what the comment says? If so, what is the point of having the comment? If not, how can we trust that the comment is telling us the truth?
It’s a pickle, so it’s best to avoid it as much as possible.
5: Always know what our code is supposed to do before we start writing it
It seems obvious, but it isn’t.
How many times have we sat down to write code without fully understanding what the code we were writing was actually supposed to do?
I’ve done it more times than I’d like to admit, so this is a rule that I need to read often.
Practicing test driven development (TDD) can help here, because we literally have to know what the code is going to do before we write it, but it still doesn’t stop us from creating the wrong thing, so it’s still important to make sure we absolutely, 100% understand the requirements of the feature or functionality we are building before we build it.

6: Test our sh—code before we ship it

Don’t just toss our code over the wall and have QA pound on it only to send it back to us so that we can waste a bunch of everyone’s time with unnecessary bug reports and resolutions.
Instead, take a few minutes to run through the test scenarios ourself, before we call our code done.
Sure, we won’t catch every bug before we pass our work on to QA, but we’ll at least catch some of the stupid and embarrassing mistakes that we all make from time-to-time.
Too many software developers think that it is only QA’s job to test their stuff. It’s simply not true. Quality is everyone’s responsibility.
wStack of open books

 7: Learn something new every day

If we didn’t learn something new today, we just made backwards progress, because I can guarantee you forgot something.
It doesn’t take a lot of time to learn something new each and every day.
The little advances  we make each and every day add up over time and will greatly shape our future. But, we have to start investing now if we want to reap the rewards later.
Besides, today technology is changing so rapidly that if we aren’t continually improving our skills and learning new ones, we are going to be left behind very quickly.

8: Writing code is fun

That’s right. We probably didn’t get into this profession just because it pays well.
I mean, there is nothing wrong with picking a job that pays well, but doctor or lawyer would have probably been a better choice.
Most likely we became a software developer, because we love wirting code. So, we don’t forget that we are doing what we love.
9: We can’t know it all
As much as you learn, there is still going to be a lot you don’t know.
It’s important to realize this because we can drive yourself nuts trying to know everything.
It’s OK to not have all the answers.
It’s OK to ask for help or to speak up when we don’t understand something.
In many cases, we can learn what we need to know pretty darn close to when you need to know it—believe me, I do it all the time.
My point is, don’t get caught up in trying to learn it all, when that is an impossible task. Instead, focus on learning what you need to know and building the skills that enable you to learn things quickly.

10: Best practices are context dependent

Is test-driven development, the best way to write code?
Should we always pair program?
Are we a scrub if we don’t use IoC containers?
The answer to all of these questions is “it depends.”
It depends on the context.
People will try to shove best practices down our throat and they’ll try to tell us that they always apply—that we should always do this or that—but, it’s simply not true.
I follow a lot of best practices when I am writing code, but I also conditionally don’t follow them as well.

11: Always strive to simplify

All problems can be broken down.
The most elegant solutions are often the most simple ones.
But, simplicity doesn’t come easy. It takes work to make things simple.
The purpose of this blog is to take some of the complexities of software development, and life in general, and make them simple.
Believe me, this isn’t an easy task.
Any fool can create a complex solution to a problem. It takes extra effort and care to refine a solution to make it simple, but still correct.
Take the time. Put forth the effort. Strive for simplicity.

Modifying an HTTP Response

Because the PHP engine interacts with the Web server, our PHP scripts can influence the HTTP response headers sent by the server. This can be very useful.
To get the Web server to send a custom HTTP header as part of its response, we will use the PHP's header() function. This simply takes the header line to output, and then injects this line into the response headers:

header( "Server: Never you mind" );

By default, the header() function replaces any HTTP header field with the same name. In the example just shown, if the response already contains a Server header, that header is replaced with the one passed into the header() function. However, some HTTP header fields can be included more than once in the response. If we'd like to include the same header several times, pass in false as the second argument to the header() function:

  1. header( "Set-Cookie: name=Fred; expires=Mon, 05-Jan-2009 10:22:21 GMT; path=/; domain=.example.com");
  2. header( "Set-Cookie: age=33; expires=Mon, 05-Jan-2009 10:22:21 GMT; path=/; domain=.example.com", false );

(Although we can set cookies this way, it's easier to use PHP's setcookie() function.)

Generally speaking, when we pass a header line to the header() function, PHP faithfully injects the header line as-is into the response. However, there are two special cases:
  • If the header string starts with HTTP/, PHP assumes we want to set the status line, rather than add or replace a header line. This allows us to set our own HTTP status lines:

    // Nothing to see here, move along
     header( "HTTP/1.1 404 Not Found" );
  • If we pass in a Location header string, PHP automatically sends a 302 Found status line as well as the Location header:

    // Redirect to the login page
     header( "Location: http://www.example.com/login.php" );
  • This makes it easy to do page redirects . If we'd rather send a different status line, simply specify the status line as well:

    header( "HTTP/1.1 301 Moved Permanently" );
    header( "Location: http://www.example.com/newpage.php" );
The header() function is very useful if our PHP script needs to send anything other than an HTML Web page. For example, say we have a report.pdf file on the Web server, and we want to send this to the browser. We could write the following:

  1. <?php
  2. header( "Content-Type: application/pdf" );
  3. readfile( "report.pdf" );
  4. ?>

The first line tells the Web browser to expect a PDF document rather than a regular Web page. The second line reads the PDF file on the server's hard drive and outputs its contents to the Web browser, which can then save or display the PDF.

Usually it's up to the browser as to whether it displays the file in the browser itself, or offers to save it to the user's hard disk. We can use a Content-Disposition: Attachment header to suggest to the browser that the file should be saved rather than displayed and, optionally, to suggest a filename for the saved file:

  1. <?php
  2. header( "Content-Type: application/pdf" );
  3. header( 'Content-Disposition: attachment; filename="Latest Report.pdf"' );
  4. readfile( "report.pdf" );
  5. ?>

By the way, we need to make sure we don't send anything to the browser before calling header(). This includes HTML markup, or even blank lines, before your opening <?php tag. This is because, once PHP has received a request to send some content to the browser, it sends the HTTP headers first (because the headers need to be sent at the start of the response). Therefore, by the time our header() call is executed, the content is already being sent, and it's too late to send any more headers. (If we fall foul of this, then our header isn't sent and PHP generates a Cannot modify header information - headers already sent warning.)

Friday, March 13, 2015

Using Exception Objects to Handle Errors

Using Exception Objects to Handle Errors

Although functions like trigger_error() and set_error_handler() give us a lot of flexibility with raising and handling errors, they do have limitations. For example, if a piece of code calls a class method and an error occurs in that method, it would be nice if the method could simply tell the calling code about the error, rather than having to raise an error with trigger_error() and go through a central error handler. That way the calling code could take action to correct the problem, making the application more robust.

One simple, common way to achieve this is to get a function or method to return a special error value, such as -1 or false. The calling code can then inspect the return value and, if it equals the error value, it knows there was a problem. However, this can get unwieldy when you start working with deeply nested function or method calls, as the following code shows:

class WarpDrive {
   public function setWarpFactor( $factor ) {
     if ( $factor >=1 && $factor <= 9 ) {
       echo "Warp factor $factor<br />";
       return true;
     } else {
       return false;
     }
   }
 }
 class ChiefEngineer {
   public function doWarp( $factor ) {
     $wd = new WarpDrive;
     return $wd->setWarpFactor( $factor );
   }
 }
 class Captain {
   public function newWarpOrder( $factor ) {
     $ce = new ChiefEngineer;
     return $ce->doWarp( $factor );
   }
 }
 $c = new Captain;
 if ( !$c->newWarpOrder( 10 ) ) echo "She cannot go any faster!<br />";

The WarpDrive::setWarpFactor() function returns true if the function succeeded, and false otherwise (if the warp factor was less than 1 or greater than 9). This return value then needs to be passed through both the ChiefEngineer::doWarp() method and the Captain::newWarpOrder() method to reach the calling code, which can then identify and report on the error. It's not uncommon to find at least this level of nested method calls in complex applications.

Another problem is that simply returning false doesn't tell the calling code much about what went wrong. What's more, when a method has to return an error value, it can't then easily return anything else (because methods and functions can return only one thing at a time).

Fortunately, PHP gives us exceptions, which are a much more elegant way of triggering and handling error conditions. Rather than returning a single error value, our method or function can create a rich Exception object that includes detailed information about the problem, then throw the object up to the calling code to handle, or catch.

Another nice feature of exceptions is that the calling code doesn't have to catch an exception if it doesn't want to; if it ignores it, the exception is re-thrown up the calling chain until it is caught. If no code catches the exception, the script halts with a fatal error and the exception is logged or displayed to the user (depending on our log_errors and display_errors settings). So by using exceptions, any problem can either be handled automatically by another part of the application or, if all else fails, reported to the developer or user. This allows applications to be much more flexible and robust in their handling of error scenarios.

Note: If we don't want uncaught exceptions to raise fatal errors, we can create our own exception handler to deal with the exceptions (much like creating our own error handler).
See http://www.php.net/manual/en/function.set-exception-handler.php for details.

Throwing Exceptions

Here's how to create and throw an exception when an error occurs in our code:

throw new Exception;

We can also pass an optional error message to the Exception object when it's created (this is generally a good idea):

throw new Exception( "Oops, something went wrong" );

If we have a lot of different error messages in our application, it can help to give each exception a numeric error code to distinguish it. To add an error code to our thrown exception, pass it as the second argument when creating the Exception object:

If we don't catch our thrown exception at some other point in our code, eventually it bubbles up to the top level of our script, displaying an error message similar to the following:

PHP Fatal error:  Uncaught exception 'Exception' with message 'Oops, something went wrong' in script.php:4
 Stack trace:
 #0 {main}
   thrown in script.php on line 4

This tells us that an exception occurred that wasn't handled by the script itself, gives us the error message, and informs us that the exception was thrown in the main (top-level) part of the script.