Skip to content

Commit 61f3ee4

Browse files
author
Phil Sturgeon
committed
Added some information about Exceptions.
1 parent 75f7a8e commit 61f3ee4

5 files changed

+83
-19
lines changed

_posts/03-03-01-Exceptions.md

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
isChild: true
3+
---
4+
5+
## Exceptions
6+
7+
Exceptions are a standard part of most popular programming languages, but they are often overlooked by PHP programmers.
8+
Languages like Ruby are extremely Exception heavy, so whenever something goes wrong such as a HTTP request failing, or
9+
a DB query goes wrong, or even if an image asset could not be found, Ruby (or the gems being used) will throw an
10+
exception to the screen meaning you instantly know there is a mistake.
11+
12+
PHP itself is fairly lax with this, and a call to `file_get_contents()` will usually just get you a `FALSE` and a warning.
13+
Many older PHP frameworks like CodeIgniter will just return a false, log a message to their proprietary logs and maybe
14+
let you use a method like `$this->upload->get_error()` to see what went wrong. The problem here is that you have to go
15+
looking for a mistake and check the docs to see what the error method is for this class, instead of having it made extremely
16+
obvious.
17+
18+
Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you
19+
stop another developer from being able to dynamically handle that error. Exceptions should be throw to make a developer aware
20+
of an error, then they can choose how to handle this. E.g:
21+
22+
{% highlight php %}
23+
<?php
24+
$email = new Fuel\Email;
25+
$email->subject('My Subject');
26+
$email->body('How the heck are you?');
27+
$email->to('[email protected]', 'Some Guy');
28+
29+
try
30+
{
31+
$email->send();
32+
}
33+
catch(Fuel\Email\ValidationFailedException $e)
34+
{
35+
// The validation failed
36+
}
37+
catch(Fuel\Email\SendingFailedException $e)
38+
{
39+
// The driver could not send the email
40+
}
41+
{% endhighlight %}
42+
43+
### SPL Exceptions
44+
45+
An Exception by default has no meaning and the most common to give it meaning is by setting its name:
46+
47+
{% highlight php %}
48+
<?php
49+
class ValidationException extends Exception {}
50+
{% endhighlight %}
51+
52+
This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to
53+
the creation of a <em>lot</em> of custom Exceptions, some of which could have been avoided using the SPL Exceptions
54+
provided in the [SPL extension][splext].
55+
56+
If for example you use the `__call()` Magic Method and an invalid method is requested then instead of throwing a standard
57+
Exception which is vague, or creating a custom Exception just for that, you could just `throw new BadFunctionCallException;`.
58+
59+
* [Read about Exceptions][exceptions]
60+
* [Read about SPL Exceptions][splexe]
61+
62+
[exceptions]: http://php.net/manual/en/language.exceptions.php
63+
[splexe]: http://php.net/manual/en/spl.exceptions.php
64+
[splext]: /#standard_php_library
File renamed without changes.

_posts/03-05-01-Command-Line-Interface.md renamed to _posts/03-06-01-Command-Line-Interface.md

+11-11
Original file line numberDiff line numberDiff line change
@@ -11,31 +11,31 @@ CLI PHP programs are powerful because you can use your app's code directly witho
1111
Try running PHP from your command line:
1212

1313
{% highlight bash %}
14-
> php -i
14+
php -i
1515
{% endhighlight %}
1616

1717
The `-i` option will print your PHP configuration just like the [`phpinfo`][phpinfo] function. There are a number of other useful [command line options][cli-options], too.
1818

1919
Let's write a simple "Hello, $name" CLI program. To try it out, create a file named `hello.php`, as below.
2020

2121
{% highlight php %}
22-
<?php
23-
if($argc != 2) {
24-
die("Usage: php hello.php [name].\n");
25-
}
26-
$name = $argv[1];
27-
echo "Hello, $name\n";
22+
<?php
23+
if($argc != 2) {
24+
die("Usage: php hello.php [name].\n");
25+
}
26+
$name = $argv[1];
27+
echo "Hello, $name\n";
2828
{% endhighlight %}
2929
3030
PHP sets up two special variables based on the arguments your script is run with. [`$argc`][argc] is an integer variable containing the argument *count* and [`$argv`][argv] is an array variable containing each argument's *value*. The first argument is always the name of your PHP script file, in this case `hello.php`.
3131
3232
To run our script, above, from the command line:
3333
3434
{% highlight bash %}
35-
> php hello.php
36-
Usage: php hello.php [name]
37-
> php hello.php world
38-
Hello, world
35+
php hello.php
36+
Usage: php hello.php [name]
37+
php hello.php world
38+
Hello, world
3939
{% endhighlight %}
4040
4141

_posts/05-01-01-Databases-and-PDO.md

+8-8
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,19 @@ More importantly, `PDO` allows you to safely inject foreign input (e.g. IDs) int
77
Let's assume a PHP script receives a numeric ID as a query parameter. This ID should be used to fetch a user record from a database. This is the `wrong` way to do this:
88

99
{% highlight php %}
10-
<?php
11-
$pdo = new PDO('sqlite:users.db');
12-
$pdo->query("SELECT name FROM users WHERE id = " . $_GET['id']); // <-- NO!
10+
<?php
11+
$pdo = new PDO('sqlite:users.db');
12+
$pdo->query("SELECT name FROM users WHERE id = " . $_GET['id']); // <-- NO!
1313
{% endhighlight %}
1414

1515
This is terrible code. You are inserting a raw query parameter into a SQL query. This will get you hacked in a heartbeat. Instead, you should sanitize the ID input using PDO bound parameters.
1616

1717
{% highlight php %}
18-
<?php
19-
$pdo = new PDO('sqlite:users.db');
20-
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id');
21-
$stmt->bindParam(':id', filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT), PDO::PARAM_INT);
22-
$stmt->execute();
18+
<?php
19+
$pdo = new PDO('sqlite:users.db');
20+
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id');
21+
$stmt->bindParam(':id', filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT), PDO::PARAM_INT);
22+
$stmt->execute();
2323
{% endhighlight %}
2424

2525
This is correct code. It uses a bound parameter on a PDO statement. This escapes the foreign input ID before it is introduced to the database preventing potential SQL injection attacks.

0 commit comments

Comments
 (0)