Fix line wrapping consistency - round 1

Comply with the 'wrap at 120 chars' style rule stated in the contributing.md document
This commit is contained in:
jrfnl
2014-12-07 23:07:49 +01:00
parent ac95e06b40
commit 82ee7ad76a
26 changed files with 348 additions and 268 deletions

View File

@@ -6,7 +6,10 @@ anchor: use_the_current_stable_version
## Use the Current Stable Version (5.6) {#use_the_current_stable_version_title}
If you are getting started with PHP, start with the current stable release of [PHP 5.6][php-release]. PHP has added powerful [new features](#language_highlights) over the last few years. Though the incremental version number difference between 5.2 and 5.6 is small, it represents _major_ improvements. If you are looking for a function or its usage, the documentation on the [php.net][php-docs] website will have the answer.
If you are getting started with PHP, start with the current stable release of [PHP 5.6][php-release]. PHP has added
powerful [new features](#language_highlights) over the last few years. Though the incremental version number difference
between 5.2 and 5.6 is small, it represents _major_ improvements. If you are looking for a function or its usage, the
documentation on the [php.net][php-docs] website will have the answer.
[php-release]: http://php.net/downloads.php
[php-docs]: http://php.net/manual/

View File

@@ -6,7 +6,8 @@ anchor: builtin_web_server
## Built-in web server {#builtin_web_server_title}
With PHP 5.4 or newer, you can start learning PHP without installing and configuring a full-fledged web server. To start the server, run the following command from your terminal in your project's web root:
With PHP 5.4 or newer, you can start learning PHP without installing and configuring a full-fledged web server.
To start the server, run the following command from your terminal in your project's web root:
{% highlight console %}
> php -S localhost:8000

View File

@@ -3,25 +3,26 @@ isChild: true
anchor: mac_setup
---
## Mac Setup {#mac_setup_title}
## Mac Setup {#mac_setup_title}
OS X comes prepackaged with PHP but it is normally a little behind the latest stable. Mountain Lion has
5.3.10, Mavericks has 5.4.17 and Yosemite has 5.5.9, but with PHP 5.6 out that is often not good enough.
OS X comes prepackaged with PHP but it is normally a little behind the latest stable. Mountain Lion has 5.3.10,
Mavericks has 5.4.17 and Yosemite has 5.5.9, but with PHP 5.6 out that is often not good enough.
There are multiple ways to install PHP on OS X.
### Install PHP via Homebrew
[Homebrew](http://brew.sh/) is a powerful package manager for OS X, which can help you install PHP and
various extensions easily. [Homebrew PHP] is a repository that contains PHP-related "formulae" for Homebrew,
and will let you install PHP.
[Homebrew](http://brew.sh/) is a powerful package manager for OS X, which can help you install PHP and various
extensions easily. [Homebrew PHP] is a repository that contains PHP-related "formulae" for Homebrew, and will let you
install PHP.
At this point, you can install `php53`, `php54`, `php55` or `php56` using the `brew install` command, and switch between them by modifying your `PATH` variable.
At this point, you can install `php53`, `php54`, `php55` or `php56` using the `brew install` command, and switch
between them by modifying your `PATH` variable.
### Install PHP via phpbrew
[phpbrew] is a tool for installing and managing multiple PHP versions. This can be really useful if two
different applications/projects require different versions of PHP, and you are not using virtual machines.
[phpbrew] is a tool for installing and managing multiple PHP versions. This can be really useful if two different
applications/projects require different versions of PHP, and you are not using virtual machines.
### Compile from Source
@@ -31,7 +32,9 @@ downloadable from Apple's Mac Developer Center.
### All-in-One Installers
The solutions listed above mainly handle PHP itself, and do not supply things like Apache, Nginx or a SQL server. "All-in-one" solutions such as [MAMP][mamp-downloads] and [XAMPP][xampp] will install these other bits of software for you and tie them all together, but ease of setup comes with a trade-off of flexibility.
The solutions listed above mainly handle PHP itself, and do not supply things like Apache, Nginx or a SQL server.
"All-in-one" solutions such as [MAMP][mamp-downloads] and [XAMPP][xampp] will install these other bits of software for
you and tie them all together, but ease of setup comes with a trade-off of flexibility.
[Homebrew]: http://brew.sh/
[Homebrew PHP]: https://github.com/Homebrew/homebrew-php#installation

View File

@@ -5,18 +5,19 @@ anchor: windows_setup
## Windows Setup {#windows_setup_title}
PHP is available in several ways for Windows. You can [download the binaries][php-downloads] and until recently you could use a '.msi'
installer. The installer is no longer supported and stops at PHP 5.3.0.
PHP is available in several ways for Windows. You can [download the binaries][php-downloads] and until recently you
could use a '.msi' installer. The installer is no longer supported and stops at PHP 5.3.0.
For learning and local development you can use the built in webserver with PHP 5.4+ so you don't need to worry about configuring it. If you
would like an "all-in-one" which includes a full-blown webserver and MySQL too then tools such as the [Web Platform Installer][wpi],
[Zend Server CE][zsce], [XAMPP][xampp], [EasyPHP][easyphp] and [WAMP][wamp] will help get a Windows development environment up and running fast. That said, these tools will be
a little different from production so be careful of environment differences if you are working on Windows and deploying to Linux.
For learning and local development you can use the built in webserver with PHP 5.4+ so you don't need to worry about
configuring it. If you would like an "all-in-one" which includes a full-blown webserver and MySQL too then tools such
as the [Web Platform Installer][wpi], [Zend Server CE][zsce], [XAMPP][xampp], [EasyPHP][easyphp] and [WAMP][wamp] will
help get a Windows development environment up and running fast. That said, these tools will be a little different from
production so be careful of environment differences if you are working on Windows and deploying to Linux.
If you need to run your production system on Windows then IIS7 will give you the most stable and best performance. You can use
[phpmanager][phpmanager] (a GUI plugin for IIS7) to make configuring and managing PHP simple. IIS7 comes with FastCGI built in and ready
to go, you just need to configure PHP as a handler. For support and additional resources there is a [dedicated area on iis.net][php-iis] for
PHP.
If you need to run your production system on Windows then IIS7 will give you the most stable and best performance. You
can use [phpmanager][phpmanager] (a GUI plugin for IIS7) to make configuring and managing PHP simple. IIS7 comes with
FastCGI built in and ready to go, you just need to configure PHP as a handler. For support and additional resources
there is a [dedicated area on iis.net][php-iis] for PHP.
[php-downloads]: http://windows.php.net
[phpmanager]: http://phpmanager.codeplex.com/

View File

@@ -2,7 +2,7 @@
anchor: code_style_guide
---
# Code Style Guide {#code_style_guide_title}
# Code Style Guide {#code_style_guide_title}
The PHP community is large and diverse, composed of innumerable libraries, frameworks, and components. It is common for
PHP developers to choose several of these and combine them into a single project. It is important that PHP code adhere
@@ -10,13 +10,14 @@ PHP developers to choose several of these and combine them into a single project
their projects.
The [Framework Interop Group][fig] has proposed and approved a series of style recommendations. Not all of them related
to code-style, but those that do are [PSR-0][psr0], [PSR-1][psr1], [PSR-2][psr2] and [PSR-4][psr4]. These recommendations
are merely a set of rules that some projects like Drupal, Zend, Symfony, CakePHP, phpBB, AWS SDK, FuelPHP, Lithium,
etc are starting to adopt. You can use them for your own projects, or continue to use your own personal style.
to code-style, but those that do are [PSR-0][psr0], [PSR-1][psr1], [PSR-2][psr2] and [PSR-4][psr4]. These
recommendations are merely a set of rules that some projects like Drupal, Zend, Symfony, CakePHP, phpBB, AWS SDK,
FuelPHP, Lithium, etc are starting to adopt. You can use them for your own projects, or continue to use your own
personal style.
Ideally you should write PHP code that adheres to a known standard. This could be any combination of PSR's, or one
of the coding standards made by PEAR or Zend. This means other developers can easily read and work with your code,
and applications that implement the components can have consistency even when working with lots of third-party code.
of the coding standards made by PEAR or Zend. This means other developers can easily read and work with your code, and
applications that implement the components can have consistency even when working with lots of third-party code.
* [Read about PSR-0][psr0]
* [Read about PSR-1][psr1]
@@ -26,17 +27,17 @@ and applications that implement the components can have consistency even when wo
* [Read about Zend Coding Standards][zend-cs]
* [Read about Symfony Coding Standards][symfony-cs]
You can use [PHP_CodeSniffer][phpcs] to check code against any one of these recommendations, and plugins for text editors
like [Sublime Text 2][st-cs] to be given real time feedback.
You can use [PHP_CodeSniffer][phpcs] to check code against any one of these recommendations, and plugins for text
editors like [Sublime Text 2][st-cs] to be given real time feedback.
You can fix the code layout automatically by using one of the two possible tools. One is Fabien Potencier's
[PHP Coding Standards Fixer][phpcsfixer] which has a very well tested codebase. It is bigger and slower, but very stable
and used by some huge projects like Magento and Symfony. Another option is [php.tools][phptools], which is made popular
by the [sublime-phpfmt][sublime-phpfmt] editor plugin. While being newer, it makes great improvements in performance,
meaning real-time editor fixing is more fluid.
[PHP Coding Standards Fixer][phpcsfixer] which has a very well tested codebase. It is bigger and slower, but very
stable and used by some huge projects like Magento and Symfony. Another option is [php.tools][phptools], which is made
popular by the [sublime-phpfmt][sublime-phpfmt] editor plugin. While being newer, it makes great improvements in
performance, meaning real-time editor fixing is more fluid.
English is preferred for all symbol names and code infrastructure. Comments may be written in any language easily readable
by all current and future parties who may be working on the codebase.
English is preferred for all symbol names and code infrastructure. Comments may be written in any language easily
readable by all current and future parties who may be working on the codebase.
[fig]: http://www.php-fig.org/
[psr0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

View File

@@ -6,8 +6,8 @@ anchor: programming_paradigms
## Programming Paradigms {#programming_paradigms_title}
PHP is a flexible, dynamic language that supports a variety of programming techniques. It has evolved dramatically over
the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in PHP 5.3
(2009), and traits in PHP 5.4 (2012).
the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in
PHP 5.3 (2009), and traits in PHP 5.4 (2012).
### Object-oriented Programming
@@ -19,12 +19,12 @@ interfaces, inheritance, constructors, cloning, exceptions, and more.
### Functional Programming
PHP supports first-class function, meaning that a function can be assigned to a variable. Both user-defined and built-in
functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to other
functions (feature called Higher-order functions) and function can return other functions.
PHP supports first-class function, meaning that a function can be assigned to a variable. Both user-defined and
built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to
other functions (feature called Higher-order functions) and function can return other functions.
Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code focus
on iteration.
Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code
focus on iteration.
New anonymous functions (with support for closures) are present since PHP 5.3 (2009).

View File

@@ -5,25 +5,24 @@ anchor: namespaces
## Namespaces {#namespaces_title}
As mentioned above, the PHP community has a lot of developers creating lots of code. This means that
one library's PHP code may use the same class name as another library. When both libraries are used
in the same namespace, they collide and cause trouble.
As mentioned above, the PHP community has a lot of developers creating lots of code. This means that one library's PHP
code may use the same class name as another library. When both libraries are used in the same namespace, they collide
and cause trouble.
_Namespaces_ solve this problem. As described in the PHP reference manual, namespaces may be compared
to operating system directories that _namespace_ files; two files with the same name may co-exist in
separate directories. Likewise, two PHP classes with the same name may co-exist in separate PHP
namespaces. It's as simple as that.
_Namespaces_ solve this problem. As described in the PHP reference manual, namespaces may be compared to operating
system directories that _namespace_ files; two files with the same name may co-exist in separate directories. Likewise,
two PHP classes with the same name may co-exist in separate PHP namespaces. It's as simple as that.
It is important for you to namespace your code so that it may be used by other developers without fear
of colliding with other libraries.
It is important for you to namespace your code so that it may be used by other developers without fear of colliding
with other libraries.
One recommended way to use namespaces is outlined in [PSR-0][psr0], which aims to provide a standard file,
class and namespace convention to allow plug-and-play code.
One recommended way to use namespaces is outlined in [PSR-0][psr0], which aims to provide a standard file, class and
namespace convention to allow plug-and-play code.
In December 2013 the PHP-FIG created a new autoloading standard: [PSR-4][psr4], which one day will
probably replace PSR-0. Currently both are still usable, as PSR-4 requires PHP 5.3 and many PHP 5.2-only
projects currently implement PSR-0. If you're going to use an autoloader standard for a new application or
package then you almost certainly want to look into PSR-4.
In December 2013 the PHP-FIG created a new autoloading standard: [PSR-4][psr4], which one day will probably replace
PSR-0. Currently both are still usable, as PSR-4 requires PHP 5.3 and many PHP 5.2-only projects currently implement
PSR-0. If you're going to use an autoloader standard for a new application or package then you almost certainly want
to look into PSR-4.
* [Read about Namespaces][namespaces]
* [Read about PSR-0][psr0]

View File

@@ -6,7 +6,9 @@ anchor: standard_php_library
## Standard PHP Library {#standard_php_library_title}
The Standard PHP Library (SPL) is packaged with PHP and provides a collection of classes and interfaces. It is made up primarily of commonly needed datastructure classes (stack, queue, heap, and so on), and iterators which can traverse over these datastructures or your own classes which implement SPL interfaces.
The Standard PHP Library (SPL) is packaged with PHP and provides a collection of classes and interfaces. It is made up
primarily of commonly needed datastructure classes (stack, queue, heap, and so on), and iterators which can traverse
over these datastructures or your own classes which implement SPL interfaces.
* [Read about the SPL][spl]

View File

@@ -5,9 +5,11 @@ anchor: command_line_interface
## Command Line Interface {#command_line_interface_title}
PHP was created to write web applications, but is also useful for scripting command line interface (CLI) programs. Command line PHP programs can help automate common tasks like testing, deployment, and application administrivia.
PHP was created to write web applications, but is also useful for scripting command line interface (CLI) programs.
Command line PHP programs can help automate common tasks like testing, deployment, and application administrivia.
CLI PHP programs are powerful because you can use your app's code directly without having to create and secure a web GUI for it. Just be sure not to put your CLI PHP scripts in your public web root!
CLI PHP programs are powerful because you can use your app's code directly without having to create and secure a web
GUI for it. Just be sure not to put your CLI PHP scripts in your public web root!
Try running PHP from your command line:
@@ -17,7 +19,8 @@ Try running PHP from your command line:
The `-i` option will print your PHP configuration just like the [`phpinfo`][phpinfo] function.
The `-a` option provides an interactive shell, similar to ruby's IRB or python's interactive shell. There are a number of other useful [command line options][cli-options], too.
The `-a` option provides an interactive shell, similar to ruby's IRB or python's interactive shell. There are a number
of other useful [command line options][cli-options], too.
Let's write a simple "Hello, $name" CLI program. To try it out, create a file named `hello.php`, as below.
@@ -31,9 +34,12 @@ $name = $argv[1];
echo "Hello, $name\n";
{% endhighlight %}
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`.
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`.
The `exit()` expression is used with a non-zero number to let the shell know that the command failed. Commonly used exit codes can be found [here][exit-codes]
The `exit()` expression is used with a non-zero number to let the shell know that the command failed. Commonly used
exit codes can be found [here][exit-codes]
To run our script, above, from the command line:

View File

@@ -8,15 +8,15 @@ anchor: xdebug
One of the most useful tools in software development is a proper debugger. It allows you to trace the execution of your
code and monitor the contents of the stack. XDebug, PHP's debugger, can be utilized by various IDEs to provide
Breakpoints and stack inspection. It can also allow tools like PHPUnit and KCacheGrind to perform code coverage analysis
and code profiling.
Breakpoints and stack inspection. It can also allow tools like PHPUnit and KCacheGrind to perform code coverage
analysis and code profiling.
If you find yourself in a bind, willing to resort to var_dump/print_r, and you still can't find the solution - maybe you
need to use the debugger.
If you find yourself in a bind, willing to resort to var_dump/print_r, and you still can't find the solution - maybe
you need to use the debugger.
[Installing XDebug][xdebug-install] can be tricky, but one of its most important features is "Remote Debugging" - if you
develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you will
want to enable right away.
[Installing XDebug][xdebug-install] can be tricky, but one of its most important features is "Remote Debugging" - if
you develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you
will want to enable right away.
Traditionally, you will modify your Apache VHost or .htaccess file with these values:
@@ -33,7 +33,7 @@ listen on. Then it's just a matter of putting your IDE into "listen for connecti
Your IDE will now intercept the current state as the script executes, allowing you to set breakpoints and probe the
values in memory.
Graphical debuggers make it very easy to step through code, inspect variables, and eval code against the live runtime.
Graphical debuggers make it very easy to step through code, inspect variables, and eval code against the live runtime.
Many IDE's have built-in or plugin-based support for graphical debugging with xdebug. MacGDBp is a free, open-source,
stand-alone xdebug GUI for Mac.

View File

@@ -4,11 +4,16 @@ anchor: dependency_management
# Dependency Management {#dependency_management_title}
There are a ton of PHP libraries, frameworks, and components to choose from. Your project will likely use several of them — these are project dependencies. Until recently, PHP did not have a good way to manage these project dependencies. Even if you managed them manually, you still had to worry about autoloaders. No more.
There are a ton of PHP libraries, frameworks, and components to choose from. Your project will likely use several of
them — these are project dependencies. Until recently, PHP did not have a good way to manage these project
dependencies. Even if you managed them manually, you still had to worry about autoloaders. No more.
Currently there are two major package management systems for PHP - Composer and PEAR. Which one is right for you? The answer is both.
Currently there are two major package management systems for PHP - Composer and PEAR. Which one is right for you? The
answer is both.
* Use **Composer** when managing dependencies for a single project.
* Use **PEAR** when managing dependencies for PHP as a whole on your system.
In general, Composer packages will be available only in the projects that you explicitly specify whereas a PEAR package would be available to all of your PHP projects. While PEAR might sound like the easier approach at first glance, there are advantages to using a project-by-project approach to your dependencies.
In general, Composer packages will be available only in the projects that you explicitly specify whereas a PEAR package
would be available to all of your PHP projects. While PEAR might sound like the easier approach at first glance, there
are advantages to using a project-by-project approach to your dependencies.

View File

@@ -5,26 +5,35 @@ anchor: composer_and_packagist
## Composer and Packagist {#composer_and_packagist_title}
Composer is a **brilliant** dependency manager for PHP. List your project's dependencies in a `composer.json` file and, with a few simple commands, Composer will automatically download your project's dependencies and setup autoloading for you.
Composer is a **brilliant** dependency manager for PHP. List your project's dependencies in a `composer.json` file and,
with a few simple commands, Composer will automatically download your project's dependencies and setup autoloading for
you.
There are already a lot of PHP libraries that are compatible with Composer, ready to be used in your project. These "packages" are listed on [Packagist][1], the official repository for Composer-compatible PHP libraries.
There are already a lot of PHP libraries that are compatible with Composer, ready to be used in your project. These
"packages" are listed on [Packagist][1], the official repository for Composer-compatible PHP libraries.
### How to Install Composer
You can install Composer locally (in your current working directory; though this is no longer recommended) or globally (e.g. /usr/local/bin). Let's assume you want to install Composer locally. From your project's root directory:
You can install Composer locally (in your current working directory; though this is no longer recommended) or globally
(e.g. /usr/local/bin). Let's assume you want to install Composer locally. From your project's root directory:
{% highlight console %}
curl -s https://getcomposer.org/installer | php
{% endhighlight %}
This will download `composer.phar` (a PHP binary archive). You can run this with `php` to manage your project dependencies. <strong>Please Note:</strong> If you pipe downloaded code directly into an interpreter, please read the code online first to confirm it is safe.
This will download `composer.phar` (a PHP binary archive). You can run this with `php` to manage your project
dependencies. <strong>Please Note:</strong> If you pipe downloaded code directly into an interpreter, please read the
code online first to confirm it is safe.
#### Installing on Windows
For Windows users the easiest way to get up and running is to use the [ComposerSetup][6] installer, which performs a global install and sets up your `$PATH` so that you can just call `composer` from any directory in your command line.
For Windows users the easiest way to get up and running is to use the [ComposerSetup][6] installer, which performs a
global install and sets up your `$PATH` so that you can just call `composer` from any directory in your command line.
### How to Install Composer (manually)
Manually installing Composer is an advanced technique; however, there are various reasons why a developer might prefer this method vs. using the interactive installation routine. The interactive installation checks your PHP installation to ensure that:
Manually installing Composer is an advanced technique; however, there are various reasons why a developer might prefer
this method vs. using the interactive installation routine. The interactive installation checks your PHP installation
to ensure that:
- a sufficient version of PHP is being used
- `.phar` files can be executed correctly
@@ -32,16 +41,19 @@ Manually installing Composer is an advanced technique; however, there are variou
- certain problematic extensions are not loaded
- certain `php.ini` settings are set
Since a manual installation performs none of these checks, you have to decide whether the trade-off is worth it for you. As such, below is how to obtain Composer manually:
Since a manual installation performs none of these checks, you have to decide whether the trade-off is worth it for
you. As such, below is how to obtain Composer manually:
{% highlight console %}
curl -s https://getcomposer.org/composer.phar -o $HOME/local/bin/composer
chmod +x $HOME/local/bin/composer
{% endhighlight %}
The path `$HOME/local/bin` (or a directory of your choice) should be in your `$PATH` environment variable. This will result in a `composer` command being available.
The path `$HOME/local/bin` (or a directory of your choice) should be in your `$PATH` environment variable. This will
result in a `composer` command being available.
When you come across documentation that states to run Composer as `php composer.phar install`, you can substitute that with:
When you come across documentation that states to run Composer as `php composer.phar install`, you can substitute that
with:
{% highlight console %}
composer install
@@ -51,19 +63,25 @@ This section will assume you have installed composer globally.
### How to Define and Install Dependencies
Composer keeps track of your project's dependencies in a file called `composer.json`. You can manage it by hand if you like, or use Composer itself. The `composer require` command adds a project dependency and if you don't have a `composer.json` file, one will be created. Here's an example that adds [Twig][2] as a dependency of your project.
Composer keeps track of your project's dependencies in a file called `composer.json`. You can manage it by hand if you
like, or use Composer itself. The `composer require` command adds a project dependency and if you don't have a
`composer.json` file, one will be created. Here's an example that adds [Twig][2] as a dependency of your project.
{% highlight console %}
composer require twig/twig:~1.8
{% endhighlight %}
Alternatively the `composer init` command will guide you through creating a full `composer.json` file for your project. Either way, once you've created your `composer.json` file you can tell Composer to download and install your dependencies into the `vendor/` directory. This also applies to projects you've downloaded that already provide a `composer.json` file:
Alternatively the `composer init` command will guide you through creating a full `composer.json` file for your project.
Either way, once you've created your `composer.json` file you can tell Composer to download and install your
dependencies into the `vendor/` directory. This also applies to projects you've downloaded that already provide a
`composer.json` file:
{% highlight console %}
composer install
{% endhighlight %}
Next, add this line to your application's primary PHP file; this will tell PHP to use Composer's autoloader for your project dependencies.
Next, add this line to your application's primary PHP file; this will tell PHP to use Composer's autoloader for your
project dependencies.
{% highlight php %}
<?php
@@ -74,9 +92,15 @@ Now you can use your project dependencies, and they'll be autoloaded on demand.
### Updating your dependencies
Composer creates a file called `composer.lock` which stores the exact version of each package it downloaded when you first ran `php composer.phar install`. If you share your project with other coders and the `composer.lock` file is part of your distribution, when they run `php composer.phar install` they'll get the same versions as you. To update your dependencies, run `php composer.phar update`.
Composer creates a file called `composer.lock` which stores the exact version of each package it downloaded when you
first ran `php composer.phar install`. If you share your project with other coders and the `composer.lock` file is
part of your distribution, when they run `php composer.phar install` they'll get the same versions as you. To update
your dependencies, run `php composer.phar update`.
This is most useful when you define your version requirements flexibly. For instance a version requirement of `~1.8` means "anything newer than `1.8.0`, but less than `2.0.x-dev`". You can also use the `*` wildcard as in `1.8.*`. Now Composer's `php composer.phar update` command will upgrade all your dependencies to the newest version that fits the restrictions you define.
This is most useful when you define your version requirements flexibly. For instance a version requirement of `~1.8`
means "anything newer than `1.8.0`, but less than `2.0.x-dev`". You can also use the `*` wildcard as in `1.8.*`. Now
Composer's `php composer.phar update` command will upgrade all your dependencies to the newest version that fits the
restrictions you define.
### Update Notifications
@@ -85,7 +109,8 @@ your GitHub and BitBucket accounts for `composer.json` files and send emails wit
### Checking your dependencies for security issues
The [Security Advisories Checker][4] is a web service and a command-line tool, both will examine your `composer.lock` file and tell you if you need to update any of your dependencies.
The [Security Advisories Checker][4] is a web service and a command-line tool, both will examine your `composer.lock`
file and tell you if you need to update any of your dependencies.
* [Learn about Composer][5]

View File

@@ -8,12 +8,12 @@ anchor: pear
Another veteran package manager that many PHP developers enjoy is [PEAR][1]. It behaves much the same way as Composer,
but has some notable differences.
PEAR requires each package to have a specific structure, which means that the author of the package must prepare it
for usage with PEAR. Using a project which was not prepared to work with PEAR is not possible.
PEAR requires each package to have a specific structure, which means that the author of the package must prepare it for
usage with PEAR. Using a project which was not prepared to work with PEAR is not possible.
PEAR installs packages globally, which means after installing them once they are available to all projects on that
server. This can be good if many projects rely on the same package with the same version but might lead to problems
if version conflicts between two projects arise.
server. This can be good if many projects rely on the same package with the same version but might lead to problems if
version conflicts between two projects arise.
### How to install PEAR
@@ -28,7 +28,7 @@ have an apt ``php-pear`` package.
If the package is listed on the [PEAR packages list][3], you can install it by specifying the official name:
{% highlight console %}
pear install foo
pear install foo
{% endhighlight %}
If the package is hosted on another channel, you need to `discover` the channel first and also specify it when
@@ -38,8 +38,8 @@ installing. See the [Using channel docs][4] for more information on this topic.
### Handling PEAR dependencies with Composer
If you are already using [Composer][5] and you would like to install some PEAR code too, you can use
Composer to handle your PEAR dependencies. This example will install code from `pear2.php.net`:
If you are already using [Composer][5] and you would like to install some PEAR code too, you can use Composer to
handle your PEAR dependencies. This example will install code from `pear2.php.net`:
{% highlight json %}
{
@@ -56,17 +56,16 @@ Composer to handle your PEAR dependencies. This example will install code from `
}
{% endhighlight %}
The first section `"repositories"` will be used to let Composer know it should "initialise"
(or "discover" in PEAR terminology) the pear repo. Then the require section will prefix the package
name like this:
The first section `"repositories"` will be used to let Composer know it should "initialise" (or "discover" in PEAR
terminology) the pear repo. Then the require section will prefix the package name like this:
> pear-channel/Package
The "pear" prefix is hardcoded to avoid any conflicts, as a pear channel could be the same as another packages vendor name for example, then the channel short name (or full URL) can be used
to reference which channel the package is in.
The "pear" prefix is hardcoded to avoid any conflicts, as a pear channel could be the same as another packages vendor
name for example, then the channel short name (or full URL) can be used to reference which channel the package is in.
When this code is installed it will be available in your vendor directory and automatically
available through the Composer autoloader:
When this code is installed it will be available in your vendor directory and automatically available through the
Composer autoloader:
> vendor/pear-pear2.php.net/PEAR2_HTTP_Request/pear2/HTTP/Request.php

View File

@@ -5,13 +5,14 @@ anchor: date_and_time
## Date and Time {#date_and_time_title}
PHP has a class named DateTime to help you when reading, writing, comparing or calculating with date and time. There are
many date and time related functions in PHP besides DateTime, but it provides nice object-oriented interface to most
common uses. It can handle time zones, but that is outside this short introduction.
PHP has a class named DateTime to help you when reading, writing, comparing or calculating with date and time. There
are many date and time related functions in PHP besides DateTime, but it provides nice object-oriented interface to
most common uses. It can handle time zones, but that is outside this short introduction.
To start working with DateTime, convert raw date and time string to an object with `createFromFormat()` factory method
or do `new DateTime` to get the current date and time. Use `format()` method to convert DateTime back to a string for
output.
{% highlight php %}
<?php
$raw = '22. 11. 1968';
@@ -22,8 +23,9 @@ echo 'Start date: ' . $start->format('Y-m-d') . "\n";
Calculating with DateTime is possible with the DateInterval class. DateTime has methods like `add()` and `sub()` that
take a DateInterval as an argument. Do not write code that expect same number of seconds in every day, both daylight
saving and timezone alterations will break that assumption. Use date intervals instead. To calculate date difference use
the `diff()` method. It will return new DateInterval, which is super easy to display.
saving and timezone alterations will break that assumption. Use date intervals instead. To calculate date difference
use the `diff()` method. It will return new DateInterval, which is super easy to display.
{% highlight php %}
<?php
// create a copy of $start and add one month and 6 days
@@ -36,6 +38,7 @@ echo 'Difference: ' . $diff->format('%m month, %d days (total: %a days)') . "\n"
{% endhighlight %}
On DateTime objects you can use standard comparison:
{% highlight php %}
<?php
if ($start < $end) {
@@ -45,6 +48,7 @@ if ($start < $end) {
One last example to demonstrate the DatePeriod class. It is used to iterate over recurring events. It can take two
DateTime objects, start and end, and the interval for which it will return all events in between.
{% highlight php %}
<?php
// output all thursdays between $start and $end

View File

@@ -32,18 +32,18 @@ string has a chance of being garbled during further processing.
Not all string functions have an `mb_*` counterpart. If there isn't one for what you want to do, then you might be out
of luck.
You should use the `mb_internal_encoding()` function at the top of every PHP script you write (or at the
top of your global include script), and the `mb_http_output()` function right after it if your script is outputting to
a browser. Explicitly defining the encoding of your strings in every script will save you a lot of headaches down the
road.
You should use the `mb_internal_encoding()` function at the top of every PHP script you write (or at the top of your
global include script), and the `mb_http_output()` function right after it if your script is outputting to a browser.
Explicitly defining the encoding of your strings in every script will save you a lot of headaches down the road.
Additionally, many PHP functions that operate on strings have an optional parameter letting you specify the character
encoding. You should always explicitly indicate UTF-8 when given the option. For example, `htmlentities()` has an
option for character encoding, and you should always specify UTF-8 if dealing with such strings. Note that as of PHP 5.4.0, UTF-8 is the default encoding for `htmlentities()` and `htmlspecialchars()`.
option for character encoding, and you should always specify UTF-8 if dealing with such strings. Note that as of PHP 5.
4.0, UTF-8 is the default encoding for `htmlentities()` and `htmlspecialchars()`.
Finally, If you are building an distributed application and cannot be certain that the `mbstring` extension will be
enabled, then consider using the [patchwork/utf8] Composer package. This
will use `mbstring` if it is available, and fall back to non UTF-8 functions if not.
enabled, then consider using the [patchwork/utf8] Composer package. This will use `mbstring` if it is available, and
fall back to non UTF-8 functions if not.
[Multibyte String Extension]: http://php.net/book.mbstring
[patchwork/utf8]: https://packagist.org/packages/patchwork/utf8
@@ -64,7 +64,10 @@ Further Reading for why.
Use the `mb_http_output()` function to ensure that your PHP script outputs UTF-8 strings to your browser.
The browser will then need to be told by the HTTP response that this page should be considered as UTF-8. The historic approach to doing that was to include the [charset `<meta>` tag](http://htmlpurifier.org/docs/enduser-utf8.html) in your page's `<head>` tag. This approach is perfectly valid, but setting the charset in the `Content-Type` header is actually [much faster](https://developers.google.com/speed/docs/best-practices/rendering#SpecifyCharsetEarly).
The browser will then need to be told by the HTTP response that this page should be considered as UTF-8. The historic
approach to doing that was to include the [charset `<meta>` tag](http://htmlpurifier.org/docs/enduser-utf8.html) in
your page's `<head>` tag. This approach is perfectly valid, but setting the charset in the `Content-Type` header is
actually [much faster](https://developers.google.com/speed/docs/best-practices/rendering#SpecifyCharsetEarly).
{% highlight php %}
<?php

View File

@@ -10,5 +10,6 @@ From [Wikipedia](http://en.wikipedia.org/wiki/Dependency_injection):
> Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it
> possible to change them, whether at run-time or compile-time.
This quote makes the concept sound much more complicated than it actually is. Dependency Injection is providing a component
with its dependencies either through constructor injection, method calls or the setting of properties. It is that simple.
This quote makes the concept sound much more complicated than it actually is. Dependency Injection is providing a
component with its dependencies either through constructor injection, method calls or the setting of properties. It is
that simple.

View File

@@ -7,9 +7,9 @@ anchor: basic_concept
We can demonstrate the concept with a simple, yet naive example.
Here we have a `Database` class that requires an adapter to speak to the database. We instantiate the
adapter in the constructor and create a hard dependency. This makes testing difficult and means the `Database` class is
very tightly coupled to the adapter.
Here we have a `Database` class that requires an adapter to speak to the database. We instantiate the adapter in the
constructor and create a hard dependency. This makes testing difficult and means the `Database` class is very tightly
coupled to the adapter.
{% highlight php %}
<?php
@@ -48,5 +48,5 @@ class MysqlAdapter {}
{% endhighlight %}
Now we are giving the `Database` class its dependency rather than it creating it itself. We could even create a method
that would accept an argument of the dependency and set it that way, or if the `$adapter` property was `public` we could
set it directly.
that would accept an argument of the dependency and set it that way, or if the `$adapter` property was `public` we
could set it directly.

View File

@@ -5,27 +5,29 @@ anchor: complex_problem
## Complex Problem {#complex_problem_title}
If you have ever read about Dependency Injection then you have probably seen the terms *"Inversion of Control"* or *"Dependency Inversion Principle"*.
These are the complex problems that Dependency Injection solves.
If you have ever read about Dependency Injection then you have probably seen the terms *"Inversion of Control"* or
*"Dependency Inversion Principle"*. These are the complex problems that Dependency Injection solves.
### Inversion of Control
Inversion of Control is as it says, "inverting the control" of a system by keeping organisational control entirely separate from our objects.
In terms of Dependency Injection, this means loosening our dependencies by controlling and instantiating them elsewhere in the system.
Inversion of Control is as it says, "inverting the control" of a system by keeping organisational control entirely
separate from our objects. In terms of Dependency Injection, this means loosening our dependencies by controlling and
instantiating them elsewhere in the system.
For years, PHP frameworks have been achieving Inversion of Control, however, the question became, which part of control
are you inverting, and where to? For example, MVC frameworks would generally provide a super object or base controller that other
controllers must extend to gain access to its dependencies. This **is** Inversion of Control, however, instead of loosening
dependencies, this method simply moved them.
are you inverting, and where to? For example, MVC frameworks would generally provide a super object or base controller
that other controllers must extend to gain access to its dependencies. This **is** Inversion of Control, however,
instead of loosening dependencies, this method simply moved them.
Dependency Injection allows us to more elegantly solve this problem by only injecting the dependencies we need, when we need them,
without the need for any hard coded dependencies at all.
Dependency Injection allows us to more elegantly solve this problem by only injecting the dependencies we need, when we
need them, without the need for any hard coded dependencies at all.
### Dependency Inversion Principle
Dependency Inversion Principle is the "D" in the S.O.L.I.D set of object oriented design principles that states one should
*"Depend on Abstractions. Do not depend on concretions."*. Put simply, this means our dependencies should be interfaces/contracts or abstract
classes rather than concrete implementations. We can easily refactor the above example to follow this principle.
Dependency Inversion Principle is the "D" in the S.O.L.I.D set of object oriented design principles that states one
should *"Depend on Abstractions. Do not depend on concretions."*. Put simply, this means our dependencies should be
interfaces/contracts or abstract classes rather than concrete implementations. We can easily refactor the above example
to follow this principle.
{% highlight php %}
<?php
@@ -48,10 +50,12 @@ class MysqlAdapter implements AdapterInterface {}
There are several benefits to the `Database` class now depending on an interface rather than a concretion.
Consider that you are working in a team and the adapter is being worked on by a colleague. In our first example, we would have
to wait for said colleague to finish the adapter before we could properly mock it for our unit tests. Now that the dependency
is an interface/contract we can happily mock that interface knowing that our colleague will build the adapter based on that contract.
Consider that you are working in a team and the adapter is being worked on by a colleague. In our first example, we
would have to wait for said colleague to finish the adapter before we could properly mock it for our unit tests. Now
that the dependency is an interface/contract we can happily mock that interface knowing that our colleague will build
the adapter based on that contract.
An even bigger benefit to this method is that our code is now much more scalable. If a year down the line we decide that we
want to migrate to a different type of database, we can write an adapter that implements the original interface and inject that instead,
no more refactoring would be required as we can ensure that the adapter follows the contract set by the interface.
An even bigger benefit to this method is that our code is now much more scalable. If a year down the line we decide
that we want to migrate to a different type of database, we can write an adapter that implements the original interface
and inject that instead, no more refactoring would be required as we can ensure that the adapter follows the contract
set by the interface.

View File

@@ -5,11 +5,12 @@ anchor: containers
## Containers {#containers_title}
The first thing you should understand about Dependency Injection Containers is that they are not the same thing as Dependency
Injection. A container is a convenience utility that helps us implement Dependency Injection, however, they can be and often
are misused to implement an anti-pattern, Service Location. Injecting a DI container as a Service Locator in to your classes arguably
creates a harder dependency on the container than the dependency you are replacing. It also makes your code much less transparent
and ultimately harder to test.
The first thing you should understand about Dependency Injection Containers is that they are not the same thing as
Dependency Injection. A container is a convenience utility that helps us implement Dependency Injection, however, they
can be and often are misused to implement an anti-pattern, Service Location. Injecting a DI container as a Service
Locator in to your classes arguably creates a harder dependency on the container than the dependency you are replacing.
It also makes your code much less transparent and ultimately harder to test.
Most modern frameworks have their own Dependency Injection Container that allows you to wire your dependencies together through configuration.
What this means in practice is that you can write application code that is as clean and de-coupled as the framework it is built on.
Most modern frameworks have their own Dependency Injection Container that allows you to wire your dependencies together
through configuration. What this means in practice is that you can write application code that is as clean and de-
coupled as the framework it is built on.

View File

@@ -6,11 +6,12 @@ anchor: databases
# Databases {#databases_title}
Many times your PHP code will use a database to persist information. You have a few options to connect and interact
with your database. The recommended option **until PHP 5.1.0** was to use native drivers such as [mysqli], [pgsql], [mssql], etc.
with your database. The recommended option **until PHP 5.1.0** was to use native drivers such as [mysqli], [pgsql],
[mssql], etc.
Native drivers are great if you are only using _one_ database in your application, but if, for example, you are using
MySQL and a little bit of MSSQL, or you need to connect to an Oracle database, then you will not be able to use the same
drivers. You'll need to learn a brand new API for each database &mdash; and that can get silly.
MySQL and a little bit of MSSQL, or you need to connect to an Oracle database, then you will not be able to use the
same drivers. You'll need to learn a brand new API for each database &mdash; and that can get silly.
## MySQL Extension
@@ -21,15 +22,17 @@ versions of PHP. This means you will be faced with a rewrite at some point down
replace mysql usage with [mysqli] or [PDO] in your applications within your own development schedules so you won't be
rushed later on.
**If you are starting from scratch then absolutely do not use the [mysql] extension: use the [MySQLi extension][mysqli], or use [PDO].**
**If you are starting from scratch then absolutely do not use the [mysql] extension: use the [MySQLi extension][mysqli],
or use [PDO].**
* [PHP: Choosing an API for MySQL](http://php.net/mysqlinfo.api.choosing)
* [PDO Tutorial for MySQL Developers](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers)
## PDO Extension
[PDO] is a database connection abstraction library &mdash; built into PHP since 5.1.0 &mdash; that provides a common interface to talk with
many different databases. For example, you can use basically identical code to interface with MySQL or SQLite:
[PDO] is a database connection abstraction library &mdash; built into PHP since 5.1.0 &mdash; that provides a common
interface to talk with many different databases. For example, you can use basically identical code to interface with
MySQL or SQLite:
{% highlight php %}
<?php
@@ -46,14 +49,15 @@ $row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);
{% endhighlight %}
PDO will not translate your SQL queries or emulate missing features; it is purely for connecting to multiple types
of database with the same API.
PDO will not translate your SQL queries or emulate missing features; it is purely for connecting to multiple types of
database with the same API.
More importantly, `PDO` allows you to safely inject foreign input (e.g. IDs) into your SQL queries without worrying about database SQL injection attacks.
More importantly, `PDO` allows you to safely inject foreign input (e.g. IDs) into your SQL queries without worrying
about database SQL injection attacks.
This is possible using PDO statements and bound parameters.
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:
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:
{% highlight php %}
<?php
@@ -62,9 +66,10 @@ $pdo->query("SELECT name FROM users WHERE id = " . $_GET['id']); // <-- NO!
{% endhighlight %}
This is terrible code. You are inserting a raw query parameter into a SQL query. This will get you hacked in a
heartbeat, using a practice called [SQL Injection](http://wiki.hashphp.org/Validation). Just imagine if a hacker passes in an inventive `id` parameter by calling a URL like
`http://domain.com/?id=1%3BDELETE+FROM+users`. This will set the `$_GET['id']` variable to `1;DELETE FROM users`
which will delete all of your users! Instead, you should sanitize the ID input using PDO bound parameters.
heartbeat, using a practice called [SQL Injection](http://wiki.hashphp.org/Validation). Just imagine if a hacker
passes in an inventive `id` parameter by calling a URL like `http://domain.com/?id=1%3BDELETE+FROM+users`. This will
set the `$_GET['id']` variable to `1;DELETE FROM users` which will delete all of your users! Instead, you should
sanitize the ID input using PDO bound parameters.
{% highlight php %}
<?php
@@ -74,15 +79,15 @@ $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); // <-- Automatically sanit
$stmt->execute();
{% endhighlight %}
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.
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.
* [Learn about PDO]
You should also be aware that database connections use up resources and it was not unheard-of to have resources
exhausted if connections were not implicitly closed, however this was more common in other languages. Using PDO you
can implicitly close the connection by destroying the object by ensuring all remaining references to it are deleted,
i.e. set to NULL. If you don't do this explicitly, PHP will automatically close the connection when your script ends -
exhausted if connections were not implicitly closed, however this was more common in other languages. Using PDO you can
implicitly close the connection by destroying the object by ensuring all remaining references to it are deleted, i.e.
set to NULL. If you don't do this explicitly, PHP will automatically close the connection when your script ends -
unless of course you are using persistent connections.
* [Learn about PDO connections]

View File

@@ -19,9 +19,11 @@ foreach ($db->query('SELECT * FROM table') as $row) {
</ul>
{% endhighlight %}
This is bad practice for all sorts of reasons, mainly that its hard to debug, hard to test, hard to read and it is going to output a lot of fields if you don't put a limit on there.
This is bad practice for all sorts of reasons, mainly that its hard to debug, hard to test, hard to read and it is
going to output a lot of fields if you don't put a limit on there.
While there are many other solutions to doing this - depending on if you prefer [OOP](/#object-oriented-programming) or [functional programming](/#functional-programming) - there must be some element of separation.
While there are many other solutions to doing this - depending on if you prefer [OOP](/#object-oriented-programming) or
[functional programming](/#functional-programming) - there must be some element of separation.
Consider the most basic step:
@@ -38,7 +40,9 @@ foreach (getAllFoos($db) as $row) {
That is a good start. Put those two items in two different files and you've got some clean separation.
Create a class to place that method in and you have a "Model". Create a simple `.php` file to put the presentation logic in and you have a "View", which is very nearly [MVC] - a common OOP architecture for most [frameworks](/#frameworks_title).
Create a class to place that method in and you have a "Model". Create a simple `.php` file to put the presentation
logic in and you have a "View", which is very nearly [MVC] - a common OOP architecture for most
[frameworks](/#frameworks_title).
**foo.php**
@@ -84,11 +88,12 @@ class Foo()
<?php endforeach ?>
{% endhighlight %}
This is essentially the same as what most modern frameworks are doing, all be it a little more manual. You might
not need to do all of that every time, but mixing together too much presentation logic and database interaction can be a real problem if you ever want to [unit-test](/#unit-testing) your application.
This is essentially the same as what most modern frameworks are doing, all be it a little more manual. You might not
need to do all of that every time, but mixing together too much presentation logic and database interaction can be a
real problem if you ever want to [unit-test](/#unit-testing) your application.
[PHPBridge] have a great resource called [Creating a Data Class] which covers a very similar topic, and is great
for developers just getting used to the concept of interacting with databases.
[PHPBridge] have a great resource called [Creating a Data Class] which covers a very similar topic, and is great for
developers just getting used to the concept of interacting with databases.
[MVC]: http://code.tutsplus.com/tutorials/mvc-for-noobs--net-10488
[PHPBridge]: http://phpbridge.org/

View File

@@ -6,12 +6,14 @@ anchor: databases_abstraction_layers
## Abstraction Layers {#databases_abstraction_layers_title}
Many frameworks provide their own abstraction layer which may or may not sit on top of PDO. These will often emulate features for
one database system that is missing from another by wrapping your queries in PHP methods, giving you actual database abstraction instead of just the connection abstraction that PDO provides.
This will of course add a little overhead, but if you are building a portable application that needs to work with MySQL, PostgreSQL and
SQLite then a little overhead will be worth it the sake of code cleanliness.
Many frameworks provide their own abstraction layer which may or may not sit on top of PDO. These will often emulate
features for one database system that is missing from another by wrapping your queries in PHP methods, giving you
actual database abstraction instead of just the connection abstraction that PDO provides. This will of course add a
little overhead, but if you are building a portable application that needs to work with MySQL, PostgreSQL and SQLite
then a little overhead will be worth it the sake of code cleanliness.
Some abstraction layers have been built using the [PSR-0][psr0] or [PSR-4][psr4] namespace standards so can be installed in any application you like:
Some abstraction layers have been built using the [PSR-0][psr0] or [PSR-4][psr4] namespace standards so can be
installed in any application you like:
* [Aura SQL][6]
* [Doctrine2 DBAL][2]

View File

@@ -5,9 +5,9 @@ title: Design Patterns
# Design Patterns
There are numerous ways to structure the code and project for your web application, and you can put as much or as little
thought as you like into architecting. But it is usually a good idea to follow common patterns because it will make
your code easier to manage and easier for others to understand.
There are numerous ways to structure the code and project for your web application, and you can put as much or as
little thought as you like into architecting. But it is usually a good idea to follow common patterns because it will
make your code easier to manage and easier for others to understand.
* [Architectural pattern on Wikipedia](https://en.wikipedia.org/wiki/Architectural_pattern)
* [Software design pattern on Wikipedia](https://en.wikipedia.org/wiki/Software_design_pattern)
@@ -15,8 +15,8 @@ your code easier to manage and easier for others to understand.
## Factory
One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates
the object you want to use. Consider the following example of the factory pattern:
One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the
object you want to use. Consider the following example of the factory pattern:
{% highlight php %}
<?php
@@ -53,9 +53,9 @@ print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron"
This code uses a factory to create the Automobile object. There are two possible benefits to building your code this
way; the first is that if you need to change, rename, or replace the Automobile class later on you can do so and you
will only have to modify the code in the factory, instead of every place in your project that uses the Automobile
class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in
the factory, instead of repeating it every time you want to create a new instance.
will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class.
The second possible benefit is that if creating the object is a complicated job you can do all of the work in the
factory, instead of repeating it every time you want to create a new instance.
Using the factory pattern isn't always necessary (or wise). The example code used here is so simple that a factory
would simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save
@@ -65,8 +65,8 @@ yourself a lot of trouble down the road by using factories.
## Singleton
When designing web applications, it often makes sense conceptually and architecturally to allow access to one and
only one instance of a particular class. The singleton pattern enables us to do this.
When designing web applications, it often makes sense conceptually and architecturally to allow access to one and only
one instance of a particular class. The singleton pattern enables us to do this.
{% highlight php %}
<?php
@@ -144,8 +144,8 @@ request lifecycle in a web application. This typically occurs when we have globa
class) or a shared resource (such as an event queue).
You should be wary when using the singleton pattern, as by its very nature it introduces global state into your
application, reducing testability. In most cases, dependency injection can (and should) be used in place of a
singleton class. Using dependency injection means that we do not introduce unnecessary coupling into the design of our
application, reducing testability. In most cases, dependency injection can (and should) be used in place of a singleton
class. Using dependency injection means that we do not introduce unnecessary coupling into the design of our
application, as the object using the shared or global resource requires no knowledge of a concretely defined class.
* [Singleton pattern on Wikipedia](https://en.wikipedia.org/wiki/Singleton_pattern)
@@ -153,11 +153,12 @@ application, as the object using the shared or global resource requires no knowl
## Strategy
With the strategy pattern you encapsulate specific families of algorithms allowing the client class responsible for
instantiating a particular algorithm to have no knowledge of the actual implementation.
There are several variations on the strategy pattern, the simplest of which is outlined below:
instantiating a particular algorithm to have no knowledge of the actual implementation. There are several variations on
the strategy pattern, the simplest of which is outlined below:
This first code snippet outlines a family of algorithms; you may want a serialized array, some JSON or maybe just an
array of data:
This first code snippet outlines a family of algorithms; you may want a serialized array, some JSON or maybe
just an array of data:
{% highlight php %}
<?php
@@ -201,6 +202,7 @@ this case 'OutputInterface'.
The next snippet of code outlines how a calling client class might use one of these algorithms and even better set the
behaviour required at runtime:
{% highlight php %}
<?php
class SomeClient
@@ -222,6 +224,7 @@ class SomeClient
The calling client class above has a private property which must be set at runtime and be of type 'OutputInterface'
once this property is set a call to loadOutput() will call the load() method in the concrete class of the output type
that has been set.
{% highlight php %}
<?php
$client = new SomeClient();
@@ -249,7 +252,11 @@ and gives you a central place to hook in code that should be run for every reque
## Model-View-Controller
The model-view-controller (MVC) pattern and its relatives HMVC and MVVM lets you break up code into logical objects that serve very specific purposes. Models serve as a data access layer where data is fetched and returned in formats usable throughout your application. Controllers handle the request, process the data returned from models and load views to send in the response. And views are display templates (markup, xml, etc) that are sent in the response to the web browser.
The model-view-controller (MVC) pattern and its relatives HMVC and MVVM lets you break up code into logical objects
that serve very specific purposes. Models serve as a data access layer where data is fetched and returned in formats
usable throughout your application. Controllers handle the request, process the data returned from models and load
views to send in the response. And views are display templates (markup, xml, etc) that are sent in the response to the
web browser.
MVC is the most common architectural pattern used in the popular [PHP frameworks](https://github.com/codeguy/php-the-right-way/wiki/Frameworks).

View File

@@ -5,16 +5,16 @@ title: Functional Programming in PHP
# Functional Programming in PHP
PHP supports first-class functions, meaning that a function can be assigned to a variable. Both user-defined and built-in
functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to other
functions and a function can return other functions (a feature called higher-order functions).
PHP supports first-class functions, meaning that a function can be assigned to a variable. Both user-defined and
built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to
other functions and a function can return other functions (a feature called higher-order functions).
Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code focus
is on iteration.
Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code
focus is on iteration.
Anonymous functions (with support for closures) have been present since PHP 5.3 (2009).
PHP 5.4 added the ability to bind closures to an object's scope and also improved support for callables such that they
PHP 5.4 added the ability to bind closures to an object's scope and also improved support for callables such that they
can be used interchangeably with anonymous functions in almost all cases.
The most common usage of higher-order functions is when implementing a strategy pattern. The built-in `array_filter`

View File

@@ -104,8 +104,8 @@ function test($a)
## Global namespace
When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this,
refer to the global function by using a backslash before the function name.
When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this, refer to
the global function by using a backslash before the function name.
{% highlight php %}
<?php
@@ -153,17 +153,17 @@ $a = 'Multi-line example' // concatenation operator (.)
### String types
Strings are a series of characters, which should sound fairly simple. That said, there are a few different types
of strings and they offer slightly different syntax, with slightly different behaviors.
Strings are a series of characters, which should sound fairly simple. That said, there are a few different types of
strings and they offer slightly different syntax, with slightly different behaviors.
#### Single quotes
Single quotes are used to denote a "literal string". Literal strings do not attempt to parse special characters
or variables.
Single quotes are used to denote a "literal string". Literal strings do not attempt to parse special characters or
variables.
If using single quotes, you could enter a variable name into a string like so: `'some $thing'`, and you would
see the exact output of `some $thing`. If using double quotes, that would try to evaluate the `$thing` variable
name and show errors if no variable was found.
If using single quotes, you could enter a variable name into a string like so: `'some $thing'`, and you would see the
exact output of `some $thing`. If using double quotes, that would try to evaluate the `$thing` variable name and show
errors if no variable was found.
{% highlight php %}
@@ -204,8 +204,8 @@ $juice = 'plum';
echo "I like $juice juice"; // Output: I like plum juice
{% endhighlight %}
When using interpolation, it is often the case that the variable will be touching another character.
This will result in some confusion as to what is the name of the variable, and what is a literal character.
When using interpolation, it is often the case that the variable will be touching another character. This will result
in some confusion as to what is the name of the variable, and what is a literal character.
To fix this problem, wrap the variable within a pair of curly brackets.
@@ -285,21 +285,21 @@ EOD; // closing 'EOD' must be on it's own line, and to th
### Which is quicker?
There is a myth floating around that single quote strings are fractionally quicker than double quote strings. This
is fundamentally not true.
There is a myth floating around that single quote strings are fractionally quicker than double quote strings. This is
fundamentally not true.
If you are defining a single string and not trying to concatenate values or anything complicated, then either a single or
double quoted string will be entirely identical. Neither are quicker.
If you are defining a single string and not trying to concatenate values or anything complicated, then either a single
or double quoted string will be entirely identical. Neither are quicker.
If you are concatenating multiple strings of any type, or interpolate values into a double quoted string, then the results can
vary. If you are working with a small number of values, concatenation is minutely faster. With a lot of values, interpolating
is minutely faster.
If you are concatenating multiple strings of any type, or interpolate values into a double quoted string, then the
results can vary. If you are working with a small number of values, concatenation is minutely faster. With a lot of
values, interpolating is minutely faster.
Regardless of what you are doing with strings, none of the types will ever have any noticable impact on your application.
Trying to rewrite code to use one or the other is always an exercise in futility, so avoid this micro-optimization unless you really
understand the meaning and impact of the differences.
Regardless of what you are doing with strings, none of the types will ever have any noticable impact on your
application. Trying to rewrite code to use one or the other is always an exercise in futility, so avoid this micro-
optimization unless you really understand the meaning and impact of the differences.
[Disproving the Single Quotes Performance Myth]: http://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html
* [Disproving the Single Quotes Performance Myth](http://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html)
## Ternary operators
@@ -334,7 +334,8 @@ return ($a == 5) ? 'yay' : 'nope'; // this example will return 'yay'
{% endhighlight %}
It should be noted that you do not need to use a ternary operator for returning a boolean value. An example of this would be.
It should be noted that you do not need to use a ternary operator for returning a boolean value. An example of this
would be.
{% highlight php %}
<?php
@@ -352,7 +353,8 @@ This can also be said for all operations(===, !==, !=, == etc).
#### Utilising brackets with ternary operators for form and function
When utilising a ternary operator, brackets can play their part to improve code readability and also to include unions within blocks of statements. An example of when there is no requirement to use bracketing is:
When utilising a ternary operator, brackets can play their part to improve code readability and also to include unions
within blocks of statements. An example of when there is no requirement to use bracketing is:
{% highlight php %}
<?php
@@ -365,7 +367,9 @@ $a = 3;
return $a == 3 ? "yay" : "nope"; // return yay or nope if $a == 3
{% endhighlight %}
Bracketing also affords us the capability of creating unions within a statement block where the block will be checked as a whole. Such as this example below which will return true if both ($a == 3 and $b == 4) are true and $c == 5 is also true.
Bracketing also affords us the capability of creating unions within a statement block where the block will be checked
as a whole. Such as this example below which will return true if both ($a == 3 and $b == 4) are true and $c == 5 is
also true.
{% highlight php %}
<?php
@@ -384,9 +388,8 @@ return ($a != 3 && $b != 4) || $c == 5;
## Variable declarations
At times, coders attempt to make their code "cleaner" by declaring predefined variables with a different name. What
this does in reality is to double the memory consumption of said script. For the example below, let us say
an example string of text contains 1MB worth of data, by copying the variable you've increased the scripts execution to
2MB.
this does in reality is to double the memory consumption of said script. For the example below, let us say an example
string of text contains 1MB worth of data, by copying the variable you've increased the scripts execution to 2MB.
{% highlight php %}
<?php