syntax highlighting for Twig examples enabled

This commit is contained in:
Peter Kokot
2014-12-11 11:30:15 +01:00
79 changed files with 1439 additions and 1091 deletions

View File

@@ -109,3 +109,4 @@ All content is completely free now, and always will be.
3. Wrap all text to 120 characters
4. Code samples should adhere to PSR-1 or higher
5. Use [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/) for all content
6. Use language agnostic urls when refering to external websites such as the [php.net](http://php.net/urlhowto.php) manual

View File

@@ -1,12 +1,15 @@
---
title: Use the Current Stable Version (5.6)
title: Use the Current Stable Version (5.6)
isChild: true
anchor: use_the_current_stable_version
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://www.php.net/downloads.php
[php-docs]: http://www.php.net/manual/en/
[php-release]: http://php.net/downloads.php
[php-docs]: http://php.net/manual/

View File

@@ -1,15 +1,19 @@
---
title: Built-in Web Server
title: Built-in Web Server
isChild: true
anchor: builtin_web_server
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:
> php -S localhost:8000
{% highlight console %}
> php -S localhost:8000
{% endhighlight %}
* [Learn about the built-in, command line web server][cli-server]
[cli-server]: http://www.php.net/manual/en/features.commandline.webserver.php
[cli-server]: http://php.net/features.commandline.webserver

View File

@@ -1,44 +1,46 @@
---
isChild: true
anchor: mac_setup
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] 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
Another option that gives you control over the version of PHP you install, is to [compile it yourself][mac-compile].
In that case be sure to have installed either Xcode or Apple's substitute ["Command Line Tools for XCode"]
downloadable from Apple's Mac Developer Center.
Another option that gives you control over the version of PHP you install, is to [compile it yourself][mac-compile].
In that case be sure to have installed either [Xcode][xcode-gcc-substitution] or Apple's substitute
["Command Line Tools for XCode"] downloadable from Apple's Mac Developer Center.
### All-in-One Installers
### 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
[mac-compile]: http://www.php.net/manual/en/install.macosx.compile.php
[phpbrew]: https://github.com/phpbrew/phpbrew
[mac-compile]: http://php.net/install.macosx.compile
[xcode-gcc-substitution]: https://github.com/kennethreitz/osx-gcc-installer
["Command Line Tools for XCode"]: https://developer.apple.com/downloads
[mamp-downloads]: http://www.mamp.info/en/downloads/
[phpbrew]: https://github.com/phpbrew/phpbrew
[xampp]: http://www.apachefriends.org/en/xampp.html

View File

@@ -1,28 +1,30 @@
---
isChild: true
anchor: windows_setup
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/
[wpi]: http://www.microsoft.com/web/downloads/platform.aspx
[zsce]: http://www.zend.com/en/products/server-ce/
[xampp]: http://www.apachefriends.org/en/xampp.html
[easyphp]: http://www.easyphp.org/
[wamp]: http://www.wampserver.com/en/
[phpmanager]: http://phpmanager.codeplex.com/
[php-iis]: http://php.iis.net/

View File

@@ -2,21 +2,22 @@
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
(as close as possible) to a common code style to make it easy for developers to mix and match various libraries for
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.
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.
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.
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.
* [Read about PSR-0][psr0]
* [Read about PSR-1][psr1]
@@ -26,17 +27,18 @@ 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

@@ -1,13 +1,13 @@
---
isChild: true
anchor: programming_paradigms
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).
@@ -36,7 +36,7 @@ can be used interchangeably with anonymous functions in almost all cases.
* [Read about the Closure class][closure-class]
* [More details in the Closures RFC][closures-rfc]
* [Read about Callables][callables]
* [Read about dynamically invoking functions with `call_user_func_array`][call-user-func-array]
* [Read about dynamically invoking functions with `call_user_func_array()`][call-user-func-array]
### Meta Programming
@@ -47,15 +47,17 @@ available as `__call()` and `__callStatic()`.
* [Read about Magic Methods][magic-methods]
* [Read about Reflection][reflection]
* [Read about Overloading][overloading]
[namespaces]: http://php.net/manual/en/language.namespaces.php
[overloading]: http://php.net/manual/en/language.oop5.overloading.php
[oop]: http://www.php.net/manual/en/language.oop5.php
[anonymous-functions]: http://www.php.net/manual/en/functions.anonymous.php
[closure-class]: http://php.net/manual/en/class.closure.php
[callables]: http://php.net/manual/en/language.types.callable.php
[magic-methods]: http://php.net/manual/en/language.oop5.magic.php
[reflection]: http://www.php.net/manual/en/intro.reflection.php
[traits]: http://www.php.net/traits
[call-user-func-array]: http://php.net/manual/en/function.call-user-func-array.php
[oop]: http://php.net/language.oop5
[traits]: http://php.net/language.oop5.traits
[anonymous-functions]: http://php.net/functions.anonymous
[closure-class]: http://php.net/class.closure
[closures-rfc]: https://wiki.php.net/rfc/closures
[callables]: http://php.net/language.types.callable
[call-user-func-array]: http://php.net/function.call-user-func-array
[magic-methods]: http://php.net/language.oop5.magic
[reflection]: http://php.net/intro.reflection
[overloading]: http://php.net/language.oop5.overloading

View File

@@ -1,34 +1,34 @@
---
isChild: true
anchor: namespaces
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]
* [Read about PSR-4][psr4]
[namespaces]: http://php.net/manual/en/language.namespaces.php
[namespaces]: http://php.net/language.namespaces
[psr0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
[psr4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md
[psr4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md

View File

@@ -1,13 +1,16 @@
---
title: Standard PHP Library
isChild: true
anchor: standard_php_library
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]
[spl]: http://php.net/manual/en/book.spl.php
[spl]: http://php.net/book.spl

View File

@@ -1,23 +1,26 @@
---
isChild: true
anchor: command_line_interface
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:
{% highlight bash %}
{% highlight console %}
> php -i
{% endhighlight %}
The `-i` option will print your PHP configuration just like the [`phpinfo`][phpinfo] function.
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,13 +34,16 @@ $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:
{% highlight bash %}
{% highlight console %}
> php hello.php
Usage: php hello.php [name]
> php hello.php world
@@ -48,10 +54,11 @@ Hello, world
* [Learn about running PHP from the command line][php-cli]
* [Learn about setting up Windows to run PHP from the command line][php-cli-windows]
[phpinfo]: http://php.net/manual/en/function.phpinfo.php
[cli-options]: http://www.php.net/manual/en/features.commandline.options.php
[argc]: http://php.net/manual/en/reserved.variables.argc.php
[argv]: http://php.net/manual/en/reserved.variables.argv.php
[php-cli]: http://php.net/manual/en/features.commandline.php
[php-cli-windows]: http://www.php.net/manual/en/install.windows.commandline.php
[exit-codes]: http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
[phpinfo]: http://php.net/function.phpinfo
[cli-options]: http://php.net/features.commandline.options
[argc]: http://php.net/reserved.variables.argc
[argv]: http://php.net/reserved.variables.argv
[exit-codes]: http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
[php-cli]: http://php.net/features.commandline
[php-cli-windows]: http://php.net/install.windows.commandline

View File

@@ -1,27 +1,29 @@
---
title: XDebug
isChild: true
anchor: xdebug
anchor: xdebug
---
## XDebug {#xdebug_title}
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:
php_value xdebug.remote_host=192.168.?.?
php_value xdebug.remote_port=9000
{% highlight ini %}
php_value xdebug.remote_host=192.168.?.?
php_value xdebug.remote_port=9000
{% endhighlight %}
The "remote host" and "remote port" will correspond to your local computer and the port that you configure your IDE to
listen on. Then it's just a matter of putting your IDE into "listen for connections" mode, and loading the URL:
@@ -31,13 +33,14 @@ 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.
Many IDE's have built-in or plugin-based support for graphical debugging with xdebug. MacGDBp is a free, open-source,
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.
* [Learn more about XDebug][xdebug-docs]
* [Learn more about MacGDBp][macgdbp-install]
[xdebug-docs]: http://xdebug.org/docs/
[xdebug-install]: http://xdebug.org/docs/install
[xdebug-docs]: http://xdebug.org/docs/
[macgdbp-install]: http://www.bluestatic.org/software/macgdbp/

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.
* 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

@@ -1,28 +1,40 @@
---
isChild: true
anchor: composer_and_packagist
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:
curl -s https://getcomposer.org/installer | php
{% 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
@@ -30,30 +42,47 @@ 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:
curl -s https://getcomposer.org/composer.phar -o $HOME/local/bin/composer
chmod +x $HOME/local/bin/composer
{% 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
{% endhighlight %}
composer install
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.
composer require twig/twig:~1.8
{% 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 `vendors/` 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:
composer install
{% 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
@@ -64,25 +93,32 @@ 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
To receive notifications about new version releases you can sign up for [VersionEye][3], a web service that can monitor
To receive notifications about new version releases you can sign up for [VersionEye][3], a web service that can monitor
your GitHub and BitBucket accounts for `composer.json` files and send emails with new package releases.
### 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]
[1]: http://packagist.org/
[2]: http://twig.sensiolabs.org
[3]: https://www.versioneye.com/
[4]: https://security.sensiolabs.org/
[5]: http://getcomposer.org/doc/00-intro.md
[6]: https://getcomposer.org/Composer-Setup.exe

View File

@@ -1,6 +1,6 @@
---
isChild: true
anchor: pear
anchor: pear
---
## PEAR {#pear_title}
@@ -8,16 +8,16 @@ 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
You can install PEAR by downloading the phar installer and executing it. The PEAR documentation has detailed
You can install PEAR by downloading the phar installer and executing it. The PEAR documentation has detailed
[install instructions][2] for every operating system.
If you are using Linux, you can also have a look at your distribution package manager. Debian and Ubuntu, for example,
@@ -27,17 +27,19 @@ 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:
pear install foo
If the package is hosted on another channel, you need to `discover` the channel first and also specify it when
{% highlight console %}
pear install foo
{% endhighlight %}
If the package is hosted on another channel, you need to `discover` the channel first and also specify it when
installing. See the [Using channel docs][4] for more information on this topic.
* [Learn about PEAR][1]
### 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 %}
{
@@ -54,28 +56,29 @@ 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
To use this PEAR package simply reference it like so:
{% highlight php %}
<?php
$request = new pear2\HTTP\Request();
{% endhighlight %}
* [Learn more about using PEAR with Composer][6]
[1]: http://pear.php.net/
[2]: http://pear.php.net/manual/en/installation.getting.php
[3]: http://pear.php.net/packages.php

View File

@@ -1,13 +1,13 @@
---
isChild: true
anchor: the_basics
anchor: the_basics
---
## The Basics {#the_basics_title}
PHP is a vast language that allows coders of all levels the ability to produce code not only quickly, but efficiently.
However while advancing through the language, we often forget the basics that we first learnt (or overlooked) in favor
of short cuts and/or bad habits. To help combat this common issue, this section is aimed at reminding coders of the
PHP is a vast language that allows coders of all levels the ability to produce code not only quickly, but efficiently.
However while advancing through the language, we often forget the basics that we first learnt (or overlooked) in favor
of short cuts and/or bad habits. To help combat this common issue, this section is aimed at reminding coders of the
basic coding practices within PHP.
* Continue reading on [The Basics](/pages/The-Basics.html)

View File

@@ -1,34 +1,36 @@
---
isChild: true
anchor: date_and_time
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
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';
$start = \DateTime::createFromFormat('d. m. Y', $raw);
$start = DateTime::createFromFormat('d. m. Y', $raw);
echo 'Start date: ' . $start->format('Y-m-d') . "\n";
{% endhighlight %}
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
$end = clone $start;
$end->add(new \DateInterval('P1M6D'));
$end->add(new DateInterval('P1M6D'));
$diff = $end->diff($start);
echo 'Difference: ' . $diff->format('%m month, %d days (total: %a days)') . "\n";
@@ -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,11 +48,12 @@ 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
$periodInterval = \DateInterval::createFromDateString('first thursday');
$periodIterator = new \DatePeriod($start, $periodInterval, $end, \DatePeriod::EXCLUDE_START_DATE);
$periodInterval = DateInterval::createFromDateString('first thursday');
$periodIterator = new DatePeriod($start, $periodInterval, $end, DatePeriod::EXCLUDE_START_DATE);
foreach ($periodIterator as $date) {
// output each date in the period
echo $date->format('Y-m-d') . ' ';
@@ -59,5 +63,5 @@ foreach ($periodIterator as $date) {
* [Read about DateTime][datetime]
* [Read about date formatting][dateformat] (accepted date format string options)
[datetime]: http://www.php.net/manual/book.datetime.php
[dateformat]: http://www.php.net/manual/function.date.php
[datetime]: http://php.net/book.datetime
[dateformat]: http://php.net/function.date

View File

@@ -1,6 +1,6 @@
---
isChild: true
anchor: design_patterns
anchor: design_patterns
---
## Design Patterns {#design_patterns_title}

View File

@@ -1,7 +1,7 @@
---
title: Working with UTF-8
title: Working with UTF-8
isChild: true
anchor: php_and_utf8
anchor: php_and_utf8
---
## Working with UTF-8 {#php_and_utf8_title}
@@ -11,60 +11,63 @@ _This section was originally written by [Alex Cabal](https://alexcabal.com/) ove
### There's no one-liner. Be careful, detailed, and consistent.
Right now PHP does not support Unicode at a low level. There are ways to ensure that UTF-8 strings are processed OK,
but it's not easy, and it requires digging in to almost all levels of the web app, from HTML to SQL to PHP. We'll aim
Right now PHP does not support Unicode at a low level. There are ways to ensure that UTF-8 strings are processed OK,
but it's not easy, and it requires digging in to almost all levels of the web app, from HTML to SQL to PHP. We'll aim
for a brief, practical summary.
### UTF-8 at the PHP level
The basic string operations, like concatenating two strings and assigning strings to variables, don't need anything
special for UTF-8. However most string functions, like `strpos()` and `strlen()`, do need special consideration. These
functions often have an `mb_*` counterpart: for example, `mb_strpos()` and `mb_strlen()`. These `mb_*` strings are made
The basic string operations, like concatenating two strings and assigning strings to variables, don't need anything
special for UTF-8. However most string functions, like `strpos()` and `strlen()`, do need special consideration. These
functions often have an `mb_*` counterpart: for example, `mb_strpos()` and `mb_strlen()`. These `mb_*` strings are made
available to you via the [Multibyte String Extension], and are specifically designed to operate on Unicode strings.
You must use the `mb_*` functions whenever you operate on a Unicode string. For example, if you use `substr()` on a
UTF-8 string, there's a good chance the result will include some garbled half-characters. The correct function to use
You must use the `mb_*` functions whenever you operate on a Unicode string. For example, if you use `substr()` on a
UTF-8 string, there's a good chance the result will include some garbled half-characters. The correct function to use
would be the multibyte counterpart, `mb_substr()`.
The hard part is remembering to use the `mb_*` functions at all times. If you forget even just once, your Unicode
The hard part is remembering to use the `mb_*` functions at all times. If you forget even just once, your Unicode
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
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()`.
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()`.
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/manual/en/book.mbstring.php
[Multibyte String Extension]: http://php.net/book.mbstring
[patchwork/utf8]: https://packagist.org/packages/patchwork/utf8
### UTF-8 at the Database level
If your PHP script accesses MySQL, there's a chance your strings could be stored as non-UTF-8 strings in the database
If your PHP script accesses MySQL, there's a chance your strings could be stored as non-UTF-8 strings in the database
even if you follow all of the precautions above.
To make sure your strings go from PHP to MySQL as UTF-8, make sure your database and tables are all set to the
`utf8mb4` character set and collation, and that you use the `utf8mb4` character set in the PDO connection string. See
To make sure your strings go from PHP to MySQL as UTF-8, make sure your database and tables are all set to the
`utf8mb4` character set and collation, and that you use the `utf8mb4` character set in the PDO connection string. See
example code below. This is _critically important_.
Note that you must use the `utf8mb4` character set for complete UTF-8 support, not the `utf8` character set! See
Note that you must use the `utf8mb4` character set for complete UTF-8 support, not the `utf8` character set! See
Further Reading for why.
### UTF-8 at the browser level
Use the `mb_http_output()` function to ensure that your PHP script outputs UTF-8 strings to your browser.
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
@@ -84,13 +87,13 @@ $string = mb_substr($string, 0, 15);
// Connect to a database to store the transformed string
// See the PDO example in this document for more information
// Note the `set names utf8mb4` commmand!
$link = new \PDO(
$link = new PDO(
'mysql:host=your-hostname;dbname=your-db;charset=utf8mb4',
'your-username',
'your-password',
array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false
)
);
@@ -128,20 +131,21 @@ header('Content-Type: text/html; charset=UTF-8');
### Further reading
* [PHP Manual: String Operations](http://php.net/manual/en/language.operators.string.php)
* [PHP Manual: String Functions](http://php.net/manual/en/ref.strings.php)
* [`strpos()`](http://php.net/manual/en/function.strpos.php)
* [`strlen()`](http://php.net/manual/en/function.strlen.php)
* [`substr()`](http://php.net/manual/en/function.substr.php)
* [PHP Manual: Multibyte String Functions](http://php.net/manual/en/ref.mbstring.php)
* [`mb_strpos()`](http://php.net/manual/en/function.mb-strpos.php)
* [`mb_strlen()`](http://php.net/manual/en/function.mb-strlen.php)
* [`mb_substr()`](http://php.net/manual/en/function.mb-substr.php)
* [`mb_internal_encoding()`](http://php.net/manual/en/function.mb-internal-encoding.php)
* [`mb_http_output()`](http://php.net/manual/en/function.mb-http-output.php)
* [`htmlentities()`](http://php.net/manual/en/function.htmlentities.php)
* [`htmlspecialchars()`](http://www.php.net/manual/en/function.htmlspecialchars.php)
* [PHP Manual: String Operations](http://php.net/language.operators.string)
* [PHP Manual: String Functions](http://php.net/ref.strings)
* [`strpos()`](http://php.net/function.strpos)
* [`strlen()`](http://php.net/function.strlen)
* [`substr()`](http://php.net/function.substr)
* [PHP Manual: Multibyte String Functions](http://php.net/ref.mbstring)
* [`mb_strpos()`](http://php.net/function.mb-strpos)
* [`mb_strlen()`](http://php.net/function.mb-strlen)
* [`mb_substr()`](http://php.net/function.mb-substr)
* [`mb_internal_encoding()`](http://php.net/function.mb-internal-encoding)
* [`mb_http_output()`](http://php.net/function.mb-http-output)
* [`htmlentities()`](http://php.net/function.htmlentities)
* [`htmlspecialchars()`](http://php.net/function.htmlspecialchars)
* [PHP UTF-8 Cheatsheet](http://blog.loftdigital.com/blog/php-utf-8-cheatsheet)
* [Handling UTF-8 with PHP](http://www.phpwact.org/php/i18n/utf-8)
* [Stack Overflow: What factors make PHP Unicode-incompatible?](http://stackoverflow.com/questions/571694/what-factors-make-php-unicode-incompatible)
* [Stack Overflow: Best practices in PHP and MySQL with international strings](http://stackoverflow.com/questions/140728/best-practices-in-php-and-mysql-with-international-strings)
* [How to support full Unicode in MySQL databases](http://mathiasbynens.be/notes/mysql-utf8mb4)

View File

@@ -1,5 +1,5 @@
---
title: Dependency Injection
title: Dependency Injection
anchor: dependency_injection
---
@@ -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

@@ -1,15 +1,15 @@
---
isChild: true
anchor: basic_concept
anchor: basic_concept
---
## Basic Concept {#basic_concept_title}
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

@@ -1,31 +1,33 @@
---
isChild: true
anchor: complex_problem
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

@@ -1,15 +1,16 @@
---
isChild: true
anchor: containers
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

@@ -1,12 +1,12 @@
---
isChild: true
anchor: further_reading
anchor: further_reading
---
## Further Reading {#further_reading_title}
- [Learning about Dependency Injection and PHP](http://ralphschindler.com/2011/05/18/learning-about-dependency-injection-and-php)
- [What is Dependency Injection?](http://fabien.potencier.org/article/11/what-is-dependency-injection)
- [Dependency Injection: An analogy](http://mwop.net/blog/260-Dependency-Injection-An-analogy.html)
- [Dependency Injection: Huh?](http://net.tutsplus.com/tutorials/php/dependency-injection-huh/)
- [Dependency Injection as a tool for testing](http://philipobenito.github.io/dependency-injection-as-a-tool-for-testing/)
* [Learning about Dependency Injection and PHP](http://ralphschindler.com/2011/05/18/learning-about-dependency-injection-and-php)
* [What is Dependency Injection?](http://fabien.potencier.org/article/11/what-is-dependency-injection)
* [Dependency Injection: An analogy](http://mwop.net/blog/260-Dependency-Injection-An-analogy.html)
* [Dependency Injection: Huh?](http://net.tutsplus.com/tutorials/php/dependency-injection-huh/)
* [Dependency Injection as a tool for testing](http://philipobenito.github.io/dependency-injection-as-a-tool-for-testing/)

View File

@@ -1,99 +1,19 @@
---
title: Databases
title: Databases
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
The [mysql] extension for PHP is no longer in active development, and is [officially deprecated as of PHP 5.5.0],
meaning that it will be removed within the next few releases. If you are using any functions that start with `mysql_*`
such as `mysql_connect()` and `mysql_query()` in your applications then these will simply not be available in later
versions of PHP. This means you will be faced with a rewrite at some point down the line, so the best option is to
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].**
* [PHP: Choosing an API for MySQL](http://php.net/manual/en/mysqlinfo.api.choosing.php)
* [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:
{% highlight php %}
<?php
// PDO + MySQL
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT some\_field FROM some\_table");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);
// PDO + SQLite
$pdo = new PDO('sqlite:/path/db/foo.sqlite');
$statement = $pdo->query("SELECT some\_field FROM some\_table");
$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.
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:
{% highlight php %}
<?php
$pdo = new PDO('sqlite:/path/db/users.db');
$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.
{% highlight php %}
<?php
$pdo = new PDO('sqlite:/path/db/users.db');
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id');
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); // <-- Automatically sanitized by PDO
$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.
* [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 -
unless of course you are using persistent connections.
* [Learn about PDO connections]
[Learn about PDO]: http://www.php.net/manual/en/book.pdo.php
[Learn about PDO connections]: http://php.net/manual/en/pdo.connections.php
[officially deprecated as of PHP 5.5.0]: http://php.net/manual/en/migration55.deprecated.php
[SQL Injection]: http://wiki.hashphp.org/Validation
[pdo]: http://php.net/pdo
[mysql]: http://php.net/mysql
[mysqli]: http://php.net/mysqli
[pgsql]: http://php.net/pgsql
[mssql]: http://php.net/mssql

View File

@@ -0,0 +1,28 @@
---
isChild: true
title: MySQL Extension
anchor: mysql_extension
---
## MySQL Extension {#mysql_extension_title}
The [mysql] extension for PHP is no longer in active development, and is [officially deprecated as of PHP 5.5.0]
[mysql_deprecated], meaning that it will be removed within the next few releases. If you are using any functions that
start with `mysql_*` such as `mysql_connect()` and `mysql_query()` in your applications then these will simply not be
available in later versions of PHP. This means you will be faced with a rewrite at some point down the line, so the
best option is to 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].**
* [PHP: Choosing an API for MySQL][mysql_api]
* [PDO Tutorial for MySQL Developers][pdo4mysql_devs]
[mysql]: http://php.net/mysql
[mysql_deprecated]: http://php.net/migration55.deprecated
[mysqli]: http://php.net/mysqli
[pdo]: http://php.net/pdo
[mysql_api]: http://php.net/mysqlinfo.api.choosing
[pdo4mysql_devs]: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

View File

@@ -1,28 +0,0 @@
---
isChild: true
title: Abstraction Layers
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.
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]
* [Propel][7]
* [ZF2 Db][4]
[1]: http://www.php.net/manual/en/book.pdo.php
[2]: http://www.doctrine-project.org/projects/dbal.html
[4]: http://packages.zendframework.com/docs/latest/manual/en/index.html#zend-db
[6]: https://github.com/auraphp/Aura.Sql
[7]: http://propelorm.org/
[psr0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
[psr4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md

View File

@@ -0,0 +1,74 @@
---
isChild: true
title: PDO Extension
anchor: pdo_extension
---
## PDO Extension {#pdo_extension_title}
[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
// PDO + MySQL
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT some\_field FROM some\_table");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);
// PDO + SQLite
$pdo = new PDO('sqlite:/path/db/foo.sqlite');
$statement = $pdo->query("SELECT some\_field FROM some\_table");
$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.
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:
{% highlight php %}
<?php
$pdo = new PDO('sqlite:/path/db/users.db');
$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]. 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
$pdo = new PDO('sqlite:/path/db/users.db');
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id');
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); // <-- Automatically sanitized by PDO
$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.
* [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 -
unless of course you are using persistent connections.
* [Learn about PDO connections]
[pdo]: http://php.net/pdo
[SQL Injection]: http://wiki.hashphp.org/Validation
[Learn about PDO]: http://php.net/book.pdo
[Learn about PDO connections]: http://php.net/pdo.connections

View File

@@ -1,12 +1,12 @@
---
isChild: true
title: Interacting with Databases
anchor: databases_interacting
title: Interacting with Databases
anchor: databases_interacting
---
## Interacting with Databases {#databases_interacting_title}
When developers first start to learn PHP, they often end up mixing their database interaction up with their
When developers first start to learn PHP, they often end up mixing their database interaction up with their
presentation logic, using code that might look like this:
{% highlight php %}
@@ -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,13 +40,14 @@ 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).
**foo.php**
{% highlight php %}
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
// Make your model available
@@ -85,11 +88,13 @@ 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

@@ -0,0 +1,30 @@
---
isChild: true
title: Abstraction Layers
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][1]. 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:
* [Aura SQL][6]
* [Doctrine2 DBAL][2]
* [Propel][7]
* [ZF2 Db][4]
[1]: http://php.net/book.pdo
[2]: http://www.doctrine-project.org/projects/dbal.html
[4]: http://packages.zendframework.com/docs/latest/manual/en/index.html#zend-db
[6]: https://github.com/auraphp/Aura.Sql
[7]: http://propelorm.org/
[psr0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
[psr4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md

View File

@@ -1,5 +1,5 @@
---
title: Templating
title: Templating
anchor: templating
---
@@ -8,5 +8,4 @@ anchor: templating
Templates provide a convenient way of separating your controller and domain logic from your presentation logic.
Templates typically contain the HTML of your application, but may also be used for other formats, such as XML.
Templates are often referred to as "views", which make up **part of** the second component of the
[modelviewcontroller](http://www.phptherightway.com/pages/Design-Patterns.html#model-view-controller) (MVC)
software architecture pattern.
[modelviewcontroller](/pages/Design-Patterns.html#model-view-controller) (MVC) software architecture pattern.

View File

@@ -1,6 +1,6 @@
---
isChild: true
anchor: templating_benefits
anchor: templating_benefits
---
## Benefits {#templating_benefits_title}

View File

@@ -1,6 +1,6 @@
---
isChild: true
anchor: plain_php_templates
anchor: plain_php_templates
---
## Plain PHP Templates {#plain_php_templates_title}
@@ -12,13 +12,12 @@ code editors already have PHP syntax highlighting and auto-completion built-in.
very fast as no compiling stage is required.
Every modern PHP framework employs some kind of template system, most of which use plain PHP by default. Outside of
frameworks, libraries like [Plates](http://platesphp.com/) or [Aura.View](https://github.com/auraphp/Aura.View) make
working with plain PHP templates easier by offering modern template functionality such as inheritance, layouts and
extensions.
frameworks, libraries like [Plates][plates] or [Aura.View][aura] make working with plain PHP templates easier by
offering modern template functionality such as inheritance, layouts and extensions.
### Simple example of a plain PHP template
Using the [Plates](http://platesphp.com/) library.
Using the [Plates][plates] library.
{% highlight php %}
<?php // user_profile.php ?>
@@ -33,7 +32,7 @@ Using the [Plates](http://platesphp.com/) library.
### Example of plain PHP templates using inheritance
Using the [Plates](http://platesphp.com/) library.
Using the [Plates][plates] library.
{% highlight php %}
<?php // template.php ?>
@@ -59,4 +58,8 @@ Using the [Plates](http://platesphp.com/) library.
<h1>User Profile</h1>
<p>Hello, <?=$this->escape($name)?></p>
{% endhighlight %}
{% endhighlight %}
[plates]: http://platesphp.com/
[aura]: https://github.com/auraphp/Aura.View

View File

@@ -1,24 +1,22 @@
---
isChild: true
anchor: compiled_templates
anchor: compiled_templates
---
## Compiled Templates {#compiled_templates}
## Compiled Templates {#compiled_templates_title}
While PHP has evolved into a mature, object oriented language, it
[hasn't improved much](http://fabien.potencier.org/article/34/templating-engines-in-php) as a templating language.
Compiled templates, like [Twig](http://twig.sensiolabs.org/) or [Smarty](http://www.smarty.net/)*, fill this void by
offering a new syntax that has been geared specifically to templating. From automatic escaping, to inheritance and
simplified control structures, compiled templates are designed to be easier to write, cleaner to read and safer to use.
Compiled templates can even be shared across different languages, [Mustache](http://mustache.github.io/) being a good
example of this. Since these templates must be compiled there is a slight performance hit, however this is very minimal
when proper caching is used.
While PHP has evolved into a mature, object oriented language, it [hasn't improved much][article_templating_engines] as
a templating language. Compiled templates, like [Twig] or [Smarty]*, fill this void by offering a new syntax that has
been geared specifically to templating. From automatic escaping, to inheritance and simplified control structures,
compiled templates are designed to be easier to write, cleaner to read and safer to use. Compiled templates can even be
shared across different languages, [Mustache] being a good example of this. Since these templates must be compiled
there is a slight performance hit, however this is very minimal when proper caching is used.
**While Smarty offers automatic escaping, this feature is NOT enabled by default.*
### Simple example of a compiled template
Using the [Twig](http://twig.sensiolabs.org/) library.
Using the [Twig] library.
{% highlight html+jinja %}
{% raw %}
@@ -33,7 +31,7 @@ Using the [Twig](http://twig.sensiolabs.org/) library.
### Example of compiled templates using inheritance
Using the [Twig](http://twig.sensiolabs.org/) library.
Using the [Twig] library.
{% highlight html+jinja %}
{% raw %}
@@ -67,3 +65,9 @@ Using the [Twig](http://twig.sensiolabs.org/) library.
{% endblock %}
{% endraw %}
{% endhighlight %}
[article_templating_engines]: http://fabien.potencier.org/article/34/templating-engines-in-php
[Twig]: http://twig.sensiolabs.org/
[Smarty]: http://www.smarty.net/
[Mustache]: http://mustache.github.io/

View File

@@ -1,28 +1,28 @@
---
isChild: true
anchor: templating_further_reading
anchor: templating_further_reading
---
## Further Reading {#templating_further_reading_title}
### Articles & Tutorials
- [Templating Engines in PHP](http://fabien.potencier.org/article/34/templating-engines-in-php)
- [An Introduction to Views & Templating in CodeIgniter](http://code.tutsplus.com/tutorials/an-introduction-to-views-templating-in-codeigniter--net-25648)
- [Getting Started With PHP Templating](http://www.smashingmagazine.com/2011/10/17/getting-started-with-php-templating/)
- [Roll Your Own Templating System in PHP](http://code.tutsplus.com/tutorials/roll-your-own-templating-system-in-php--net-16596)
- [Master Pages](https://laracasts.com/series/laravel-from-scratch/episodes/7)
- [Working With Templates in Symfony 2](http://code.tutsplus.com/tutorials/working-with-templates-in-symfony-2--cms-21172)
* [Templating Engines in PHP](http://fabien.potencier.org/article/34/templating-engines-in-php)
* [An Introduction to Views & Templating in CodeIgniter](http://code.tutsplus.com/tutorials/an-introduction-to-views-templating-in-codeigniter--net-25648)
* [Getting Started With PHP Templating](http://www.smashingmagazine.com/2011/10/17/getting-started-with-php-templating/)
* [Roll Your Own Templating System in PHP](http://code.tutsplus.com/tutorials/roll-your-own-templating-system-in-php--net-16596)
* [Master Pages](https://laracasts.com/series/laravel-from-scratch/episodes/7)
* [Working With Templates in Symfony 2](http://code.tutsplus.com/tutorials/working-with-templates-in-symfony-2--cms-21172)
### Libraries
- [Aura.View](https://github.com/auraphp/Aura.View) *(native)*
- [Blade](http://laravel.com/docs/templates) *(compiled, framework specific)*
- [Dwoo](http://dwoo.org/) *(compiled)*
- [Latte](https://github.com/nette/latte) *(compiled)*
- [Mustache](https://github.com/bobthecow/mustache.php) *(compiled)*
- [PHPTAL](http://phptal.org/) *(compiled)*
- [Plates](http://platesphp.com/) *(native)*
- [Smarty](http://www.smarty.net/) *(compiled)*
- [Twig](http://twig.sensiolabs.org/) *(compiled)*
- [Zend\View](http://framework.zend.com/manual/2.3/en/modules/zend.view.quick-start.html) *(native, framework specific)*
* [Aura.View](https://github.com/auraphp/Aura.View) *(native)*
* [Blade](http://laravel.com/docs/templates) *(compiled, framework specific)*
* [Dwoo](http://dwoo.org/) *(compiled)*
* [Latte](https://github.com/nette/latte) *(compiled)*
* [Mustache](https://github.com/bobthecow/mustache.php) *(compiled)*
* [PHPTAL](http://phptal.org/) *(compiled)*
* [Plates](http://platesphp.com/) *(native)*
* [Smarty](http://www.smarty.net/) *(compiled)*
* [Twig](http://twig.sensiolabs.org/) *(compiled)*
* [Zend\View](http://framework.zend.com/manual/2.3/en/modules/zend.view.quick-start.html) *(native, framework specific)*

View File

@@ -1,5 +1,5 @@
---
title: Errors and Exceptions
title: Errors and Exceptions
anchor: errors_and_exceptions
---

View File

@@ -1,6 +1,6 @@
---
isChild: true
anchor: errors
anchor: errors
---
## Errors {#errors_title}
@@ -12,16 +12,16 @@ processing regardless of what happens, unless a fatal error occurs.
For example:
{% highlight php %}
{% highlight console %}
$ php -a
php > echo $foo;
Notice: Undefined variable: foo in php shell code on line 1
{% endhighlight %}
This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from "exception-heavy"
languages, because referencing a missing variable in Python for example will throw an exception:
This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from
"exception-heavy" languages, because referencing a missing variable in Python for example will throw an exception:
{% highlight python %}
{% highlight console %}
$ python
>>> print foo
Traceback (most recent call last):
@@ -31,102 +31,129 @@ NameError: name 'foo' is not defined
The only real difference is that Python will freak out over any small thing, so that developers can be super sure any
potential issue or edge-case is caught, whereas PHP will keep on processing unless something extreme happens, at which
point it will throw an error and report it.
point it will throw an error and report it.
### Error Severity
PHP has several levels of error severity. The three most common types of messages are errors, notices and warnings.
These have different levels of severity; `E_ERROR`, `E_NOTICE`, and `E_WARNING`. Errors are fatal run-time errors and
are usually caused by faults in your code and need to be fixed as they'll cause PHP to stop executing. Notices are advisory messages caused by code that may or may not cause problems during the execution of the script, execution is not halted. Warnings are non-fatal errors, execution of the script will not be halted.
PHP has several levels of error severity. The three most common types of messages are errors, notices and warnings.
These have different levels of severity; `E_ERROR`, `E_NOTICE`, and `E_WARNING`. Errors are fatal run-time errors and
are usually caused by faults in your code and need to be fixed as they'll cause PHP to stop executing. Notices are
advisory messages caused by code that may or may not cause problems during the execution of the script, execution is
not halted. Warnings are non-fatal errors, execution of the script will not be halted.
Another type of error message reported at compile time are `E_STRICT` messages. These messages are used to suggest
changes to your code to help ensure best interoperability and forward compatibility with upcoming versions of PHP.
### Changing PHP's Error Reporting Behaviour
Error Reporting can be changed by using PHP settings and/or PHP function calls. Using the built in PHP function
`error_reporting()` you can set the level of errors for the duration of the script execution by passing one of the
predefined error level constants, meaning if you only want to see Warnings and Errors - but not Notices - then
you can configure that:
Error Reporting can be changed by using PHP settings and/or PHP function calls. Using the built in PHP function
`error_reporting()` you can set the level of errors for the duration of the script execution by passing one of the
predefined error level constants, meaning if you only want to see Warnings and Errors - but not Notices - then you can
configure that:
{% highlight php %}
<?php
error_reporting(E_ERROR | E_WARNING);
{% endhighlight %}
You can also control whether or not errors are displayed to the screen (good for development) or hidden, and logged
You can also control whether or not errors are displayed to the screen (good for development) or hidden, and logged
(good for production). For more information on this check out the [Error Reporting][errorreport] section.
### Inline Error Suppression
You can also tell PHP to suppress specific errors with the Error Control Operator `@`. You put
this operator at the beginning of an expression, and any error that's a direct result of the expression is silenced.
You can also tell PHP to suppress specific errors with the Error Control Operator `@`. You put this operator at the
beginning of an expression, and any error that's a direct result of the expression is silenced.
{% highlight php %}
<?php
echo @$foo['bar'];
{% endhighlight %}
This will output `$foo['bar']` if it exists, but will simply return a null and print nothing if the variable `$foo` or
`'bar'` key does not exist. Without the error control operator, this expression could create a `PHP Notice: Undefined variable: foo` or `PHP Notice: Undefined index: bar` error.
This will output `$foo['bar']` if it exists, but will simply return a null and print nothing if the variable `$foo` or
`'bar'` key does not exist. Without the error control operator, this expression could create a `PHP Notice: Undefined
variable: foo` or `PHP Notice: Undefined index: bar` error.
This might seem like a good idea, but there are a few undesirable tradeoffs. PHP handles expressions using an `@` in a less performant way than expressions without an `@`. Premature optimization may be the root of all programming arguments, but if performance is particularly important for your application/library it's important to understand the error control operator's performance implications.
This might seem like a good idea, but there are a few undesirable tradeoffs. PHP handles expressions using an `@` in a
less performant way than expressions without an `@`. Premature optimization may be the root of all programming
arguments, but if performance is particularly important for your application/library it's important to understand the
error control operator's performance implications.
Secondly, the error control operator **completely** swallows the error. The error is not displayed, and the error is not sent to the error log. Also, stock/production PHP systems have no way to turn off the error control operator. While you may be correct that the error you're seeing is harmless, a different, less harmless error will be just as silent.
Secondly, the error control operator **completely** swallows the error. The error is not displayed, and the error is
not sent to the error log. Also, stock/production PHP systems have no way to turn off the error control operator. While
you may be correct that the error you're seeing is harmless, a different, less harmless error will be just as silent.
If there's a way to avoid the error suppression operator, you should consider it. For example, our code above could be rewritten like this
If there's a way to avoid the error suppression operator, you should consider it. For example, our code above could be
rewritten like this:
{% highlight php %}
<?php
echo isset($foo['bar']) ? $foo['bar'] : '';
{% endhighlight %}
One instance where error suppression might make sense is where `fopen()` fails to find a file to load. You could check
for the existence of the file before you try to load it, but if the file is deleted after the check and before the `fopen()`
(which might sound impossible, but it can happen) then `fopen()` will return false _and_ throw an error. This is
potentially something PHP should resolve, but is one case where error suppression might seem like the only valid
One instance where error suppression might make sense is where `fopen()` fails to find a file to load. You could check
for the existence of the file before you try to load it, but if the file is deleted after the check and before the
`fopen()` (which might sound impossible, but it can happen) then `fopen()` will return false _and_ throw an error. This
is potentially something PHP should resolve, but is one case where error suppression might seem like the only valid
solution.
Earlier we mentioned there's no way in a stock PHP system to turn off the error control operator. However, [xDebug] has an `xdebug.scream` ini setting which will disable the error control operator. You can set this via your `php.ini` file with the following.
Earlier we mentioned there's no way in a stock PHP system to turn off the error control operator. However, [xDebug] has
an `xdebug.scream` ini setting which will disable the error control operator. You can set this via your `php.ini` file
with the following.
xdebug.scream = On
{% highlight ini %}
xdebug.scream = On
{% endhighlight %}
You can also set this value at runtime with the `ini_set` function
{% highlight php %}
<?php
ini_set('xdebug.scream', '1')
{% endhighlight %}
The "[Scream]" PHP extension offers similar functionality to xDebug's, although Scream's ini setting is named `scream.enabled`.
The "[Scream]" PHP extension offers similar functionality to xDebug's, although Scream's ini setting is named
`scream.enabled`.
This is most useful when you're debugging code and suspect an informative error is suppressed. Use scream with care, and as a temporary debugging tool. There's lots of PHP library code that may not work with the error control operator disabled.
This is most useful when you're debugging code and suspect an informative error is suppressed. Use scream with care,
and as a temporary debugging tool. There's lots of PHP library code that may not work with the error control operator
disabled.
* [Error Control Operators](http://php.net/manual/en/language.operators.errorcontrol.php)
* [SitePoint](http://www.sitepoint.com/)
* [Error Control Operators]
* [SitePoint]
* [xDebug]
* [Scream]
[xDebug]: http://xdebug.org/docs/basic
[Scream]: http://www.php.net/manual/en/book.scream.php
### ErrorException
PHP is perfectly capable of being an "exception-heavy" programming language, and only requires a few lines of code to
make the switch. Basically you can throw your "errors" as "exceptions" using the `ErrorException` class, which extends the `Exception` class.
PHP is perfectly capable of being an "exception-heavy" programming language, and only requires a few lines of code to
make the switch. Basically you can throw your "errors" as "exceptions" using the `ErrorException` class, which extends
the `Exception` class.
This is a common practice implemented by a large number of modern frameworks such as Symfony and Laravel. By default
Laravel will display all errors as exceptions using the [Whoops!] package if the `app.debug` switch is turned on, then
hide them if the switch is turned off.
This is a common practice implemented by a large number of modern frameworks such as Symfony and Laravel. By default
Laravel will display all errors as exceptions using the [Whoops!] package if the `app.debug` switch is turned on, then
hide them if the switch is turned off.
By throwing errors as exceptions in development you can handle them better than the usual result, and if you see an
exception during development you can wrap it in a catch statement with specific instructions on how to handle the situation. Each exception you catch instantly makes your application that little bit more robust.
By throwing errors as exceptions in development you can handle them better than the usual result, and if you see an
exception during development you can wrap it in a catch statement with specific instructions on how to handle the
situation. Each exception you catch instantly makes your application that little bit more robust.
More information on this and details on how to use `ErrorException` with error handling can be found at
[ErrorException Class][errorexception].
More information on this and details on how to use `ErrorException` with error handling can be found at
[ErrorException Class][errorexception].
* [Error Control Operators](http://php.net/manual/en/language.operators.errorcontrol.php)
* [Predefined Constants for Error Handling](http://www.php.net/manual/en/errorfunc.constants.php)
* [error_reporting](http://www.php.net/manual/en/function.error-reporting.php)
* [Error Control Operators]
* [Predefined Constants for Error Handling]
* [`error_reporting()`][error_reporting]
* [Reporting][errorreport]
[errorexception]: http://php.net/manual/en/class.errorexception.php
[errorreport]: /#error_reporting
[xDebug]: http://xdebug.org/docs/basic
[Scream]: http://php.net/book.scream
[Error Control Operators]: http://php.net/language.operators.errorcontrol
[SitePoint]: http://www.sitepoint.com/
[Whoops!]: http://filp.github.io/whoops/
[errorexception]: http://php.net/class.errorexception
[Predefined Constants for Error Handling]: http://php.net/errorfunc.constants
[error_reporting]: http://php.net/function.error-reporting

View File

@@ -1,24 +1,25 @@
---
isChild: true
anchor: exceptions
anchor: exceptions
---
## Exceptions {#exceptions_title}
Exceptions are a standard part of most popular programming languages, but they are often overlooked by PHP programmers.
Languages like Ruby are extremely Exception heavy, so whenever something goes wrong such as a HTTP request failing, or
a DB query goes wrong, or even if an image asset could not be found, Ruby (or the gems being used) will throw an
exception to the screen meaning you instantly know there is a mistake.
Exceptions are a standard part of most popular programming languages, but they are often overlooked by PHP programmers.
Languages like Ruby are extremely Exception heavy, so whenever something goes wrong such as a HTTP request failing, or
a DB query goes wrong, or even if an image asset could not be found, Ruby (or the gems being used) will throw an
exception to the screen meaning you instantly know there is a mistake.
PHP itself is fairly lax with this, and a call to `file_get_contents()` will usually just get you a `FALSE` and a warning.
Many older PHP frameworks like CodeIgniter will just return a false, log a message to their proprietary logs and maybe
let you use a method like `$this->upload->get_error()` to see what went wrong. The problem here is that you have to go
looking for a mistake and check the docs to see what the error method is for this class, instead of having it made extremely
obvious.
PHP itself is fairly lax with this, and a call to `file_get_contents()` will usually just get you a `FALSE` and a
warning.
Many older PHP frameworks like CodeIgniter will just return a false, log a message to their proprietary logs and maybe
let you use a method like `$this->upload->get_error()` to see what went wrong. The problem here is that you have to go
looking for a mistake and check the docs to see what the error method is for this class, instead of having it made
extremely obvious.
Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you
stop another developer from being able to dynamically handle that error. Exceptions should be thrown to make a developer
aware of an error; they then can choose how to handle this. E.g.:
Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you
stop another developer from being able to dynamically handle that error. Exceptions should be thrown to make a
developer aware of an error; they then can choose how to handle this. E.g.:
{% highlight php %}
<?php
@@ -47,28 +48,30 @@ finally
### SPL Exceptions
The generic `Exception` class provides very little debugging context for the developer; however, to remedy this,
it is possible to create a specialized `Exception` type by sub-classing the generic `Exception` class:
The generic `Exception` class provides very little debugging context for the developer; however, to remedy this, it is
possible to create a specialized `Exception` type by sub-classing the generic `Exception` class:
{% highlight php %}
<?php
class ValidationException extends Exception {}
{% endhighlight %}
This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to
the creation of a <em>lot</em> of custom Exceptions, some of which could have been avoided using the SPL Exceptions
provided in the [SPL extension][splext].
This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to the
creation of a <em>lot</em> of custom Exceptions, some of which could have been avoided using the SPL Exceptions
provided in the [SPL extension][splext].
If for example you use the `__call()` Magic Method and an invalid method is requested then instead of throwing a standard
Exception which is vague, or creating a custom Exception just for that, you could just `throw new BadMethodCallException;`.
If for example you use the `__call()` Magic Method and an invalid method is requested then instead of throwing a
standard Exception which is vague, or creating a custom Exception just for that, you could just
`throw new BadMethodCallException;`.
* [Read about Exceptions][exceptions]
* [Read about SPL Exceptions][splexe]
* [Nesting Exceptions In PHP][nesting-exceptions-in-php]
* [Exception Best Practices in PHP 5.3][exception-best-practices53]
[exceptions]: http://php.net/manual/en/language.exceptions.php
[splexe]: http://php.net/manual/en/spl.exceptions.php
[splext]: /#standard_php_library
[exception-best-practices53]: http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3
[exceptions]: http://php.net/language.exceptions
[splexe]: http://php.net/spl.exceptions
[nesting-exceptions-in-php]: http://www.brandonsavage.net/exceptional-php-nesting-exceptions-in-php/
[exception-best-practices53]: http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3

View File

@@ -1,14 +1,17 @@
---
isChild: true
anchor: web_application_security
anchor: web_application_security
---
## Web Application Security {#web_application_security_title}
There are bad people ready and willing to exploit your web application. It is important that you
take necessary precautions to harden your web application's security. Luckily, the fine folks at [The Open Web Application Security Project][1] (OWASP) have compiled a comprehensive list of known security issues and methods to protect yourself against them. This is a must read for the security-conscious developer.
There are bad people ready and willing to exploit your web application. It is important that you take necessary
precautions to harden your web application's security. Luckily, the fine folks at
[The Open Web Application Security Project][1] (OWASP) have compiled a comprehensive list of known security issues and
methods to protect yourself against them. This is a must read for the security-conscious developer.
* [Read the OWASP Security Guide][2]
[1]: https://www.owasp.org/
[2]: https://www.owasp.org/index.php/Guide_Table_of_Contents

View File

@@ -1,23 +1,31 @@
---
isChild: true
anchor: password_hashing
anchor: password_hashing
---
## Password Hashing {#password_hashing_title}
Eventually everyone builds a PHP application that relies on user login. Usernames and passwords are stored in a database and later used to authenticate users upon login.
Eventually everyone builds a PHP application that relies on user login. Usernames and passwords are stored in a
database and later used to authenticate users upon login.
It is important that you properly [_hash_][3] passwords before storing them. Password hashing is an irreversible, one way function performed against the user's password. This produces a fixed-length string that cannot be feasibly reversed. This means you can compare a hash against another to determine if they both came from the same source string, but you cannot determine the original string. If passwords are not hashed and your database is accessed by an unauthorized third-party, all user accounts are now compromised. Some users may (unfortunately) use the same password for other services. Therefore, it is important to take security seriously.
It is important that you properly [_hash_][3] passwords before storing them. Password hashing is an irreversible, one
way function performed against the user's password. This produces a fixed-length string that cannot be feasibly
reversed. This means you can compare a hash against another to determine if they both came from the same source string,
but you cannot determine the original string. If passwords are not hashed and your database is accessed by an
unauthorized third-party, all user accounts are now compromised. Some users may (unfortunately) use the same password
for other services. Therefore, it is important to take security seriously.
**Hashing passwords with `password_hash`**
In PHP 5.5 `password_hash` was introduced. At this time it is using BCrypt, the strongest algorithm currently supported by PHP. It will be updated in the future to support more algorithms as needed though. The `password_compat` library was created to provide forward compatibility for PHP >= 5.3.7.
In PHP 5.5 `password_hash()` was introduced. At this time it is using BCrypt, the strongest algorithm currently
supported by PHP. It will be updated in the future to support more algorithms as needed though. The `password_compat`
library was created to provide forward compatibility for PHP >= 5.3.7.
Below we hash a string, and then check the hash against a new string. Because our two source strings are different ('secret-password' vs. 'bad-password') this login will fail.
Below we hash a string, and then check the hash against a new string. Because our two source strings are different
('secret-password' vs. 'bad-password') this login will fail.
{% highlight php %}
<?php
require 'password.php';
$passwordHash = password_hash('secret-password', PASSWORD_DEFAULT);
@@ -30,13 +38,13 @@ if (password_verify('bad-password', $passwordHash)) {
{% endhighlight %}
* [Learn about `password_hash`] [1]
* [`password_compat` for PHP >= 5.3.7 && < 5.5] [2]
* [Learn about `password_hash()`] [1]
* [`password_compat` for PHP >= 5.3.7 && < 5.5] [2]
* [Learn about hashing in regards to cryptography] [3]
* [PHP `password_hash` RFC] [4]
* [PHP `password_hash()` RFC] [4]
[1]: http://us2.php.net/manual/en/function.password-hash.php
[1]: http://php.net/function.password-hash
[2]: https://github.com/ircmaxell/password_compat
[3]: http://en.wikipedia.org/wiki/Cryptographic_hash_function
[4]: https://wiki.php.net/rfc/password_hash

View File

@@ -1,37 +1,34 @@
---
isChild: true
anchor: data_filtering
anchor: data_filtering
---
## Data Filtering {#data_filtering_title}
Never ever (ever) trust foreign input introduced to your PHP code. Always sanitize and validate
foreign input before using it in code. The `filter_var` and `filter_input` functions can sanitize text and validate text formats (e.g.
Never ever (ever) trust foreign input introduced to your PHP code. Always sanitize and validate foreign input before
using it in code. The `filter_var()` and `filter_input()` functions can sanitize text and validate text formats (e.g.
email addresses).
Foreign input can be anything: `$_GET` and `$_POST` form input data, some values in the `$_SERVER`
superglobal, and the HTTP request body via `fopen('php://input', 'r')`. Remember, foreign input is not
limited to form data submitted by the user. Uploaded and downloaded files, session values, cookie data,
and data from third-party web services are foreign input, too.
Foreign input can be anything: `$_GET` and `$_POST` form input data, some values in the `$_SERVER` superglobal, and the
HTTP request body via `fopen('php://input', 'r')`. Remember, foreign input is not limited to form data submitted by the
user. Uploaded and downloaded files, session values, cookie data, and data from third-party web services are foreign
input, too.
While foreign data can be stored, combined, and accessed later, it is still foreign input. Every
time you process, output, concatenate, or include data in your code, ask yourself if
the data is filtered properly and can it be trusted.
While foreign data can be stored, combined, and accessed later, it is still foreign input. Every time you process,
output, concatenate, or include data in your code, ask yourself if the data is filtered properly and can it be trusted.
Data may be _filtered_ differently based on its purpose. For example, when unfiltered foreign input is passed
into HTML page output, it can execute HTML and JavaScript on your site! This is known as Cross-Site
Scripting (XSS) and can be a very dangerous attack. One way to avoid XSS is to sanitize all user-generated
data before outputting it to your page by removing HTML tags with the `strip_tags` function or escaping
characters with special meaning into their respective HTML entities with the `htmlentities`
or `htmlspecialchars` functions.
Data may be _filtered_ differently based on its purpose. For example, when unfiltered foreign input is passed into HTML
page output, it can execute HTML and JavaScript on your site! This is known as Cross-Site Scripting (XSS) and can be a
very dangerous attack. One way to avoid XSS is to sanitize all user-generated data before outputting it to your page by
removing HTML tags with the `strip_tags()` function or escaping characters with special meaning into their respective
HTML entities with the `htmlentities()` or `htmlspecialchars()` functions.
Another example is passing options to be executed on the command line. This can be extremely dangerous
(and is usually a bad idea), but you can use the built-in `escapeshellarg` function to sanitize the executed
command's arguments.
Another example is passing options to be executed on the command line. This can be extremely dangerous (and is usually
a bad idea), but you can use the built-in `escapeshellarg()` function to sanitize the executed command's arguments.
One last example is accepting foreign input to determine a file to load from the filesystem. This can be exploited by
changing the filename to a file path. You need to remove "/", "../", [null bytes][6], or other characters from the file path so it can't
load hidden, non-public, or sensitive files.
changing the filename to a file path. You need to remove `"/"`, `"../"`, [null bytes][6], or other characters from the
file path so it can't load hidden, non-public, or sensitive files.
* [Learn about data filtering][1]
* [Learn about `filter_var`][4]
@@ -42,28 +39,27 @@ load hidden, non-public, or sensitive files.
Sanitization removes (or escapes) illegal or unsafe characters from foreign input.
For example, you should sanitize foreign input before including the input in HTML or inserting it
into a raw SQL query. When you use bound parameters with [PDO](#databases), it will
sanitize the input for you.
For example, you should sanitize foreign input before including the input in HTML or inserting it into a raw SQL query.
When you use bound parameters with [PDO](#databases), it will sanitize the input for you.
Sometimes it is required to allow some safe HTML tags in the input when including it in the HTML
page. This is very hard to do and many avoid it by using other more restricted formatting like
Markdown or BBCode, although whitelisting libraries like [HTML Purifier][html-purifier] exists for
this reason.
Sometimes it is required to allow some safe HTML tags in the input when including it in the HTML page. This is very
hard to do and many avoid it by using other more restricted formatting like Markdown or BBCode, although whitelisting
libraries like [HTML Purifier][html-purifier] exists for this reason.
[See Sanitization Filters][2]
### Validation
Validation ensures that foreign input is what you expect. For example, you may want to validate an
email address, a phone number, or age when processing a registration submission.
Validation ensures that foreign input is what you expect. For example, you may want to validate an email address, a
phone number, or age when processing a registration submission.
[See Validation Filters][3]
[1]: http://www.php.net/manual/en/book.filter.php
[2]: http://www.php.net/manual/en/filter.filters.sanitize.php
[3]: http://www.php.net/manual/en/filter.filters.validate.php
[4]: http://php.net/manual/en/function.filter-var.php
[5]: http://www.php.net/manual/en/function.filter-input.php
[6]: http://php.net/manual/en/security.filesystem.nullbytes.php
[1]: http://php.net/book.filter
[2]: http://php.net/filter.filters.sanitize
[3]: http://php.net/filter.filters.validate
[4]: http://php.net/function.filter-var
[5]: http://php.net/function.filter-input
[6]: http://php.net/security.filesystem.nullbytes
[html-purifier]: http://htmlpurifier.org/

View File

@@ -1,16 +1,16 @@
---
isChild: true
anchor: configuration_files
anchor: configuration_files
---
## Configuration Files {#configuration_files_title}
When creating configuration files for your applications, best practices recommend that one of the following methods
be followed:
When creating configuration files for your applications, best practices recommend that one of the following methods be
followed:
- It is recommended that you store your configuration information where it cannot be accessed directly and pulled in
- It is recommended that you store your configuration information where it cannot be accessed directly and pulled in
via the file system.
- If you must store your configuration files in the document root, name the files with a `.php` extension. This
ensures that, even if the script is accessed directly, it will not be output as plain text.
- Information in configuration files should be protected accordingly, either through encryption or group/user file
- If you must store your configuration files in the document root, name the files with a `.php` extension. This ensures
that, even if the script is accessed directly, it will not be output as plain text.
- Information in configuration files should be protected accordingly, either through encryption or group/user file
system permissions

View File

@@ -1,18 +1,18 @@
---
isChild: true
anchor: register_globals
anchor: register_globals
---
## Register Globals {#register_globals_title}
**NOTE:** As of PHP 5.4.0 the `register_globals` setting has been removed and can no
longer be used. This is only included as a warning for anyone in the process of upgrading a legacy application.
**NOTE:** As of PHP 5.4.0 the `register_globals` setting has been removed and can no longer be used. This is only
included as a warning for anyone in the process of upgrading a legacy application.
When enabled, the `register_globals` configuration setting that makes several types of variables (including ones from
`$_POST`, `$_GET` and `$_REQUEST`) available in the global scope of your application. This can easily lead to
security issues as your application cannot effectively tell where the data is coming from.
When enabled, the `register_globals` configuration setting that makes several types of variables (including ones from
`$_POST`, `$_GET` and `$_REQUEST`) available in the global scope of your application. This can easily lead to security
issues as your application cannot effectively tell where the data is coming from.
For example: `$_GET['foo']` would be available via `$foo`, which can override variables that have not been declared.
For example: `$_GET['foo']` would be available via `$foo`, which can override variables that have not been declared.
If you are using PHP < 5.4.0 __make sure__ that `register_globals` is __off__.
* [Register_globals in the PHP manual](http://www.php.net/manual/en/security.globals.php)
* [Register_globals in the PHP manual](http://php.net/security.globals)

View File

@@ -1,30 +1,33 @@
---
isChild: true
anchor: error_reporting
anchor: error_reporting
---
## Error Reporting {#error_reporting_title}
Error logging can be useful in finding the problem spots in your application, but it can also expose information about
the structure of your application to the outside world. To effectively protect your application from issues that could
be caused by the output of these messages, you need to configure your server differently in development versus
Error logging can be useful in finding the problem spots in your application, but it can also expose information about
the structure of your application to the outside world. To effectively protect your application from issues that could
be caused by the output of these messages, you need to configure your server differently in development versus
production (live).
### Development
To show every possible error during <strong>development</strong>, configure the following settings in your `php.ini`:
display_errors = On
display_startup_errors = On
error_reporting = -1
log_errors = On
{% highlight ini %}
display_errors = On
display_startup_errors = On
error_reporting = -1
log_errors = On
{% endhighlight %}
> Passing in the value `-1` will show every possible error, even when new levels and constants are added in future PHP versions. The `E_ALL` constant also behaves this way as of PHP 5.4. - [php.net](http://php.net/manual/function.error-reporting.php)
> Passing in the value `-1` will show every possible error, even when new levels and constants are added in future PHP
> versions. The `E_ALL` constant also behaves this way as of PHP 5.4. -
> [php.net](http://php.net/function.error-reporting)
The `E_STRICT` error level constant was introduced in 5.3.0 and is not
part of `E_ALL`, however it became part of `E_ALL` in 5.4.0. What does this mean?
In terms of reporting every possible error in version 5.3 it means you must
use either `-1` or `E_ALL | E_STRICT`.
The `E_STRICT` error level constant was introduced in 5.3.0 and is not part of `E_ALL`, however it became part of
`E_ALL` in 5.4.0. What does this mean? In terms of reporting every possible error in version 5.3 it means you must
use either `-1` or `E_ALL | E_STRICT`.
**Reporting every possible error by PHP version**
@@ -36,15 +39,17 @@ use either `-1` or `E_ALL | E_STRICT`.
To hide errors on your <strong>production</strong> environment, configure your `php.ini` as:
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL
log_errors = On
{% highlight ini %}
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL
log_errors = On
{% endhighlight %}
With these settings in production, errors will still be logged to the error logs for the web server, but will not be
With these settings in production, errors will still be logged to the error logs for the web server, but will not be
shown to the user. For more information on these settings, see the PHP manual:
* [error_reporting](http://php.net/manual/errorfunc.configuration.php#ini.error-reporting)
* [display_errors](http://php.net/manual/errorfunc.configuration.php#ini.display-errors)
* [display_startup_errors](http://php.net/manual/errorfunc.configuration.php#ini.display-startup-errors)
* [log_errors](http://php.net/manual/errorfunc.configuration.php#ini.log-errors)
* [error_reporting](http://php.net/errorfunc.configuration#ini.error-reporting)
* [display_errors](http://php.net/errorfunc.configuration#ini.display-errors)
* [display_startup_errors](http://php.net/errorfunc.configuration#ini.display-startup-errors)
* [log_errors](http://php.net/errorfunc.configuration#ini.log-errors)

View File

@@ -4,10 +4,10 @@ anchor: testing
# Testing {#testing_title}
Writing automated tests for your PHP code is considered a best practice and can lead to well-built
applications. Automated tests are a great tool for making sure your application
does not break when you are making changes or adding new functionality and should not be ignored.
Writing automated tests for your PHP code is considered a best practice and can lead to well-built applications.
Automated tests are a great tool for making sure your application does not break when you are making changes or adding
new functionality and should not be ignored.
There are several different types of testing tools (or frameworks) available for PHP, which use
different approaches - all of which are trying to avoid manual testing and the need for large
Quality Assurance teams, just to make sure recent changes didn't break existing functionality.
There are several different types of testing tools (or frameworks) available for PHP, which use different approaches -
all of which are trying to avoid manual testing and the need for large Quality Assurance teams, just to make sure
recent changes didn't break existing functionality.

View File

@@ -1,35 +1,39 @@
---
isChild: true
anchor: test_driven_development
anchor: test_driven_development
---
## Test Driven Development {#test_driven_development_title}
From [Wikipedia](http://en.wikipedia.org/wiki/Test-driven_development):
> Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finally refactors the new code to acceptable standards. Kent Beck, who is credited with having developed or 'rediscovered' the technique, stated in 2003 that TDD encourages simple designs and inspires confidence
> Test-driven development (TDD) is a software development process that relies on the repetition of a very short
> development cycle: first the developer writes a failing automated test case that defines a desired improvement or new
> function, then produces code to pass that test and finally refactors the new code to acceptable standards. Kent Beck,
> who is credited with having developed or 'rediscovered' the technique, stated in 2003 that TDD encourages simple
> designs and inspires confidence.
There are several different types of testing that you can do for your application
There are several different types of testing that you can do for your application:
### Unit Testing
Unit Testing is a programming approach to ensure functions, classes and methods are working as
expected, from the point you build them all the way through the development cycle. By checking
values going in and out of various functions and methods, you can make sure the internal logic is
working correctly. By using Dependency Injection and building "mock" classes and stubs you can verify that dependencies are correctly used for even better test coverage.
Unit Testing is a programming approach to ensure functions, classes and methods are working as expected, from the point
you build them all the way through the development cycle. By checking values going in and out of various functions and
methods, you can make sure the internal logic is working correctly. By using Dependency Injection and building "mock"
classes and stubs you can verify that dependencies are correctly used for even better test coverage.
When you create a class or function you should create a unit test for each behavior it must have. At a very basic level you should
make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments.
This will help ensure that when you make changes to this class or function later on in the development
cycle that the old functionality continues to work as expected. The only alternative to this would be
var_dump() in a test.php, which is no way to build an application - large or small.
When you create a class or function you should create a unit test for each behavior it must have. At a very basic level
you should make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments. This
will help ensure that when you make changes to this class or function later on in the development cycle that the old
functionality continues to work as expected. The only alternative to this would be `var_dump()` in a test.php, which is
no way to build an application - large or small.
The other use for unit tests is contributing to open source. If you can write a test that shows broken
functionality (i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If
you run a project which accepts pull requests then you should suggest this as a requirement.
The other use for unit tests is contributing to open source. If you can write a test that shows broken functionality
(i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If you run a project
which accepts pull requests then you should suggest this as a requirement.
[PHPUnit](http://phpunit.de) is the de-facto testing framework for writing unit tests for PHP
applications, but there are several alternatives
[PHPUnit](http://phpunit.de) is the de-facto testing framework for writing unit tests for PHP applications, but there
are several alternatives
* [atoum](https://github.com/atoum/atoum)
* [Enhance PHP](https://github.com/Enhance-PHP/Enhance-PHP)
@@ -41,17 +45,21 @@ applications, but there are several alternatives
From [Wikipedia](http://en.wikipedia.org/wiki/Integration_testing):
> Integration testing (sometimes called Integration and Testing, abbreviated "I&T") is the phase in software testing in which individual software modules are combined and tested as a group. It occurs after unit testing and before validation testing. Integration testing takes as its input modules that have been unit tested, groups them in larger aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the integrated system ready for system testing.
> Integration testing (sometimes called Integration and Testing, abbreviated "I&T") is the phase in software testing in
> which individual software modules are combined and tested as a group. It occurs after unit testing and before
> validation testing. Integration testing takes as its input modules that have been unit tested, groups them in larger
> aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the
> integrated system ready for system testing.
Many of the same tools that can be used for unit testing can be used for integration testing as many
of the same principles are used.
Many of the same tools that can be used for unit testing can be used for integration testing as many of the same
principles are used.
### Functional Testing
Sometimes also known as acceptance testing, functional testing consists of using tools to create automated
tests that actually use your application instead of just verifying that individual units of code are behaving
correctly and that individual units can speak to each other correctly. These tools typically work using real
data and simulating actual users of the application.
Sometimes also known as acceptance testing, functional testing consists of using tools to create automated tests that
actually use your application instead of just verifying that individual units of code are behaving correctly and that
individual units can speak to each other correctly. These tools typically work using real data and simulating actual
users of the application.
#### Functional Testing Tools

View File

@@ -1,23 +1,31 @@
---
isChild: true
anchor: behavior_driven_development
anchor: behavior_driven_development
---
## Behavior Driven Development {#behavior_driven_development_title}
There are two different types of Behavior-Driven Development (BDD): SpecBDD and StoryBDD. SpecBDD focuses on technical behavior of code, while StoryBDD focuses on business or feature behaviors or interactions. PHP has frameworks for both types of BDD.
There are two different types of Behavior-Driven Development (BDD): SpecBDD and StoryBDD. SpecBDD focuses on technical
behavior of code, while StoryBDD focuses on business or feature behaviors or interactions. PHP has frameworks for both
types of BDD.
With StoryBDD, you write human-readable stories that describe the behavior of your application. These stories
can then be run as actual tests against your application. The framework used in PHP applications for StoryBDD
is Behat, which is inspired by Ruby's [Cucumber](http://cukes.info/) project and implements the Gherkin DSL
for describing feature behavior.
With StoryBDD, you write human-readable stories that describe the behavior of your application. These stories can then
be run as actual tests against your application. The framework used in PHP applications for StoryBDD is [Behat], which
is inspired by Ruby's [Cucumber] project and implements the Gherkin DSL for describing feature behavior.
With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing
a function or method, you are describing how that function or method should behave. PHP offers the PHPSpec framework for this purpose. This framework is inspired
by the [RSpec project](http://rspec.info/) for Ruby.
With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing a function
or method, you are describing how that function or method should behave. PHP offers the [PHPSpec] framework for this
purpose. This framework is inspired by the [RSpec project][Rspec] for Ruby.
### BDD Links
* [Behat](http://behat.org/), the StoryBDD framework for PHP, inspired by Ruby's [Cucumber](http://cukes.info/) project;
* [PHPSpec](http://www.phpspec.net/), the SpecBDD framework for PHP, inspired by Ruby's [RSpec](http://rspec.info/) project;
* [Codeception](http://codeception.com) is a full-stack testing framework that uses BDD principles.
* [Behat], the StoryBDD framework for PHP, inspired by Ruby's [Cucumber] project;
* [PHPSpec], the SpecBDD framework for PHP, inspired by Ruby's [RSpec] project;
* [Codeception] is a full-stack testing framework that uses BDD principles.
[Behat]: http://behat.org/
[Cucumber]: http://cukes.info/
[PHPSpec]: http://www.phpspec.net/
[RSpec]: http://rspec.info/
[Codeception]: http://codeception.com/

View File

@@ -1,14 +1,24 @@
---
isChild: true
anchor: complementary_testing_tools
anchor: complementary_testing_tools
---
## Complementary Testing Tools {#complementary_testing_tools_title}
Besides individual testing and behavior driven frameworks, there are also a number of generic frameworks and helper libraries useful for any preferred approach taken.
Besides individual testing and behavior driven frameworks, there are also a number of generic frameworks and helper
libraries useful for any preferred approach taken.
### Tool Links
* [Selenium](http://seleniumhq.org/) is a browser automation tool which can be [integrated with PHPUnit](http://phpunit.de/manual/current/en/selenium.html)
* [Mockery](https://github.com/padraic/mockery) is a Mock Object Framework which can be integrated with [PHPUnit](http://phpunit.de/) or [PHPSpec](http://www.phpspec.net/)
* [Prophecy](https://github.com/phpspec/prophecy) is a highly opinionated yet very powerful and flexible PHP object mocking framework. It's integrated with [PHPSpec](http://www.phpspec.net/) and can be used with [PHPUnit](http://phpunit.de/).
* [Selenium] is a browser automation tool which can be [integrated with PHPUnit]
* [Mockery] is a Mock Object Framework which can be integrated with [PHPUnit] or [PHPSpec]
* [Prophecy] is a highly opinionated yet very powerful and flexible PHP object mocking framework. It's integrated with
[PHPSpec] and can be used with [PHPUnit].
[Selenium]: http://seleniumhq.org/
[integrated with PHPUnit]: http://phpunit.de/manual/current/en/selenium.html
[Mockery]: https://github.com/padraic/mockery
[PHPUnit]: http://phpunit.de/
[PHPSpec]: http://www.phpspec.net/
[Prophecy]: https://github.com/phpspec/prophecy

View File

@@ -1,13 +1,13 @@
---
title: Platform as a Service (PaaS)
title: Platform as a Service (PaaS)
isChild: true
anchor: platform_as_a_service
anchor: platform_as_a_service
---
## Platform as a Service (PaaS) {#platform_as_a_service_title}
## Platform as a Service (PaaS) {#platform_as_a_service_title}
PaaS provides the system and network architecture necessary to run PHP applications on the web. This means little to no
configuration for launching PHP applications or PHP frameworks.
PaaS provides the system and network architecture necessary to run PHP applications on the web. This means little to no
configuration for launching PHP applications or PHP frameworks.
Recently PaaS has become a popular method for deploying, hosting, and scaling PHP applications of all sizes. You can
find a list of [PHP PaaS "Platform as a Service" providers](#php-paas-providers) in our [resources section](#resources).
Recently PaaS has become a popular method for deploying, hosting, and scaling PHP applications of all sizes. You can
find a list of [PHP PaaS "Platform as a Service" providers](#php_paas_providers) in our [resources section](#resources).

View File

@@ -1,29 +1,53 @@
---
isChild: true
anchor: virtual_or_dedicated_servers
anchor: virtual_or_dedicated_servers
---
## Virtual or Dedicated Servers {#virtual_or_dedicated_servers_title}
If you are comfortable with systems administration, or are interested in learning it, virtual or dedicated servers give you complete control of your application's production environment.
If you are comfortable with systems administration, or are interested in learning it, virtual or dedicated servers give
you complete control of your application's production environment.
### nginx and PHP-FPM
PHP, via PHP's built-in FastCGI Process Manager (FPM), pairs really nicely with [nginx](http://nginx.org), which is a lightweight, high-performance web server. It uses less memory than Apache and can better handle more concurrent requests. This is especially important on virtual servers that don't have much memory to spare.
PHP, via PHP's built-in FastCGI Process Manager (FPM), pairs really nicely with [nginx], which is a lightweight,
high-performance web server. It uses less memory than Apache and can better handle more concurrent requests. This is
especially important on virtual servers that don't have much memory to spare.
* [Read more on nginx](http://nginx.org)
* [Read more on PHP-FPM](http://php.net/manual/en/install.fpm.php)
* [Read more on setting up nginx and PHP-FPM securely](https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/)
* [Read more on nginx][nginx]
* [Read more on PHP-FPM][phpfpm]
* [Read more on setting up nginx and PHP-FPM securely][secure-nginx-phpfpm]
### Apache and PHP
PHP and Apache have a long history together. Apache is wildly configurable and has many available [modules](http://httpd.apache.org/docs/2.4/mod/) to extend functionality. It is a popular choice for shared servers and an easy setup for PHP frameworks and open source apps like WordPress. Unfortunately, Apache uses more resources than nginx by default and cannot handle as many visitors at the same time.
PHP and Apache have a long history together. Apache is wildly configurable and has many available
[modules][apache-modules] to extend functionality. It is a popular choice for shared servers and an easy setup for PHP
frameworks and open source apps like WordPress. Unfortunately, Apache uses more resources than nginx by default and
cannot handle as many visitors at the same time.
Apache has several possible configurations for running PHP. The most common and easiest to setup is the [prefork MPM](http://httpd.apache.org/docs/2.4/mod/prefork.html) with mod_php5. While it isn't the most memory efficient, it is the simplest to get working and to use. This is probably the best choice if you don't want to dig too deeply into the server administration aspects. Note that if you use mod_php5 you MUST use the prefork MPM.
Apache has several possible configurations for running PHP. The most common and easiest to setup is the [prefork MPM]
with mod_php5. While it isn't the most memory efficient, it is the simplest to get working and to use. This is probably
the best choice if you don't want to dig too deeply into the server administration aspects. Note that if you use
mod_php5 you MUST use the prefork MPM.
Alternatively, if you want to squeeze more performance and stability out of Apache then you can take advantage of the same FPM system as nginx and run the [worker MPM](http://httpd.apache.org/docs/2.4/mod/worker.html) or [event MPM](http://httpd.apache.org/docs/2.4/mod/event.html) with mod_fastcgi or mod_fcgid. This configuration will be significantly more memory efficient and much faster but it is more work to set up.
Alternatively, if you want to squeeze more performance and stability out of Apache then you can take advantage of the
same FPM system as nginx and run the [worker MPM] or [event MPM] with mod_fastcgi or mod_fcgid. This configuration will
be significantly more memory efficient and much faster but it is more work to set up.
* [Read more on Apache](http://httpd.apache.org/)
* [Read more on Multi-Processing Modules](http://httpd.apache.org/docs/2.4/mod/mpm_common.html)
* [Read more on mod_fastcgi](http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html)
* [Read more on mod_fcgid](http://httpd.apache.org/mod_fcgid/)
* [Read more on Apache][apache]
* [Read more on Multi-Processing Modules][apache-MPM]
* [Read more on mod_fastcgi][mod_fastcgi]
* [Read more on mod_fcgid][mod_fcgid]
[nginx]: http://nginx.org/
[phpfpm]: http://php.net/install.fpm
[secure-nginx-phpfpm]: https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/
[apache-modules]: http://httpd.apache.org/docs/2.4/mod/
[prefork MPM]: http://httpd.apache.org/docs/2.4/mod/prefork.html
[worker MPM]: http://httpd.apache.org/docs/2.4/mod/worker.html
[event MPM]: http://httpd.apache.org/docs/2.4/mod/event.html
[apache]: http://httpd.apache.org/
[apache-MPM]: http://httpd.apache.org/docs/2.4/mod/mpm_common.html
[mod_fastcgi]: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html
[mod_fcgid]: http://httpd.apache.org/mod_fcgid/

View File

@@ -1,8 +1,12 @@
---
isChild: true
anchor: shared_servers
anchor: shared_servers
---
## Shared Servers {#shared_servers_title}
PHP has shared servers to thank for its popularity. It is hard to find a host without PHP installed, but be sure it's the latest version. Shared servers allow you and other developers to deploy websites to a single machine. The upside to this is that it has become a cheap commodity. The downside is that you never know what kind of a ruckus your neighboring tenants are going to create; loading down the server or opening up security holes are the main concerns. If your project's budget can afford to avoid shared servers you should.
PHP has shared servers to thank for its popularity. It is hard to find a host without PHP installed, but be sure it's
the latest version. Shared servers allow you and other developers to deploy websites to a single machine. The upside to
this is that it has become a cheap commodity. The downside is that you never know what kind of a ruckus your
neighboring tenants are going to create; loading down the server or opening up security holes are the main concerns. If
your project's budget can afford to avoid shared servers you should.

View File

@@ -1,15 +1,14 @@
---
isChild: true
anchor: building_and_deploying_your_application
anchor: building_and_deploying_your_application
---
## Building and Deploying your Application {#building_and_deploying_your_application_title}
If you find yourself doing manual database schema changes or running your tests manually before updating your files
(manually), think twice! With every additional manual task needed to deploy a new version of your app, the chances for
potentially fatal mistakes increase. Whether you're dealing with a simple update, a comprehensive build process or
even a continuous integration strategy, [build automation](http://en.wikipedia.org/wiki/Build_automation) is your
friend.
If you find yourself doing manual database schema changes or running your tests manually before updating your files
(manually), think twice! With every additional manual task needed to deploy a new version of your app, the chances for
potentially fatal mistakes increase. Whether you're dealing with a simple update, a comprehensive build process or even
a continuous integration strategy, [build automation][buildautomation] is your friend.
Among the tasks you might want to automate are:
@@ -23,53 +22,70 @@ Among the tasks you might want to automate are:
### Build Automation Tools
Build tools can be described as a collection of scripts that handle common tasks of software deployment. The build
tool is not a part of your software, it acts on your software from 'outside'.
Build tools can be described as a collection of scripts that handle common tasks of software deployment. The build tool
is not a part of your software, it acts on your software from 'outside'.
There are many open source tools available to help you with build automation, some are written in PHP others aren't.
There are many open source tools available to help you with build automation, some are written in PHP others aren't.
This shouldn't hold you back from using them, if they're better suited for the specific job. Here are a few examples:
[Phing](http://www.phing.info/) is the easiest way to get started with automated deployment in the PHP world. With
Phing you can control your packaging, deployment or testing process from within a simple XML build file. Phing (which
is based on [Apache Ant](http://ant.apache.org/)) provides a rich set of tasks usually needed to install or update a
web app and can be extended with additional custom tasks, written in PHP.
[Phing] is the easiest way to get started with automated deployment in the PHP world. With Phing you can control your
packaging, deployment or testing process from within a simple XML build file. Phing (which is based on [Apache Ant])
provides a rich set of tasks usually needed to install or update a web app and can be extended with additional custom
tasks, written in PHP.
[Capistrano](https://github.com/capistrano/capistrano/wiki) is a system for *intermediate-to-advanced programmers* to
execute commands in a structured, repeatable way on one or more remote machines. It is pre-configured for deploying
Ruby on Rails applications, however people are **successfully deploying PHP systems** with it. Successful use of
Capistrano depends on a working knowledge of Ruby and Rake.
[Capistrano] is a system for *intermediate-to-advanced programmers* to execute commands in a structured, repeatable way
on one or more remote machines. It is pre-configured for deploying Ruby on Rails applications, however people are **
successfully deploying PHP systems** with it. Successful use of Capistrano depends on a working knowledge of Ruby and
Rake.
Dave Gardner's blog post [PHP Deployment with Capistrano](http://www.davegardner.me.uk/blog/2012/02/13/php-deployment-with-capistrano/)
is a good starting point for PHP developers interested in Capistrano.
Dave Gardner's blog post [PHP Deployment with Capistrano][phpdeploy_capistrano] is a good starting point for PHP
developers interested in Capistrano.
[Chef](http://www.opscode.com/chef/) is more than a deployment framework, it is a very powerful Ruby based system
integration framework that doesn't just deploy your app but can build your whole server environment or virtual boxes.
[Chef] is more than a deployment framework, it is a very powerful Ruby based system integration framework that doesn't
just deploy your app but can build your whole server environment or virtual boxes.
Chef resources for PHP developers:
#### Chef resources for PHP developers:
* [Three part blog series about deploying a LAMP application with Chef, Vagrant, and EC2](http://www.jasongrimes.org/2012/06/managing-lamp-environments-with-chef-vagrant-and-ec2-1-of-3/)
* [Chef Cookbook which installs and configures PHP 5.3 and the PEAR package management system](https://github.com/opscode-cookbooks/php)
* [Chef video tutorial series by Opscode, the makers of chef](https://www.youtube.com/playlist?list=PLrmstJpucjzWKt1eWLv88ZFY4R1jW8amR)
Further reading:
* [Three part blog series about deploying a LAMP application with Chef, Vagrant, and EC2][chef_vagrant_and_ec2]
* [Chef Cookbook which installs and configures PHP 5.3 and the PEAR package management system][Chef_cookbook]
* [Chef video tutorial series][Chef_tutorial] by Opscode, the makers of chef
* [Automate your project with Apache Ant](http://net.tutsplus.com/tutorials/other/automate-your-projects-with-apache-ant/)
#### Further reading:
* [Automate your project with Apache Ant][apache_ant_tutorial]
### Continuous Integration
> Continuous Integration is a software development practice where members of a team integrate their work frequently,
> usually each person integrates at least daily — leading to multiple integrations per day. Many teams find that this
> approach leads to significantly reduced integration problems and allows a team to develop cohesive software more
> Continuous Integration is a software development practice where members of a team integrate their work frequently,
> usually each person integrates at least daily — leading to multiple integrations per day. Many teams find that this
> approach leads to significantly reduced integration problems and allows a team to develop cohesive software more
> rapidly.
*-- Martin Fowler*
There are different ways to implement continuous integration for PHP. Recently [Travis CI](https://travis-ci.org/) has
done a great job of making continuous integration a reality even for small projects. Travis CI is a hosted continuous
integration service for the open source community. It is integrated with GitHub and offers first class support for many
languages including PHP.
There are different ways to implement continuous integration for PHP. Recently [Travis CI] has done a great job of
making continuous integration a reality even for small projects. Travis CI is a hosted continuous integration service
for the open source community. It is integrated with GitHub and offers first class support for many languages including
PHP.
Further reading:
#### Further reading:
* [Continuous Integration with Jenkins](http://jenkins-ci.org/)
* [Continuous Integration with PHPCI](http://www.phptesting.org/)
* [Continuous Integration with Teamcity](http://www.jetbrains.com/teamcity/)
* [Continuous Integration with Jenkins][Jenkins]
* [Continuous Integration with PHPCI][PHPCI]
* [Continuous Integration with Teamcity][Teamcity]
[buildautomation]: http://en.wikipedia.org/wiki/Build_automation
[Phing]: http://www.phing.info/
[Apache Ant]: http://ant.apache.org/
[Capistrano]: https://github.com/capistrano/capistrano/wiki
[phpdeploy_capistrano]: http://www.davegardner.me.uk/blog/2012/02/13/php-deployment-with-capistrano/
[Chef]: http://www.opscode.com/chef/
[chef_vagrant_and_ec2]: http://www.jasongrimes.org/2012/06/managing-lamp-environments-with-chef-vagrant-and-ec2-1-of-3/
[Chef_cookbook]: https://github.com/opscode-cookbooks/php
[Chef_tutorial]: https://www.youtube.com/playlist?list=PLrmstJpucjzWKt1eWLv88ZFY4R1jW8amR
[apache_ant_tutorial]: http://net.tutsplus.com/tutorials/other/automate-your-projects-with-apache-ant/
[Travis CI]: https://travis-ci.org/
[Jenkins]: http://jenkins-ci.org/
[PHPCI]: http://www.phptesting.org/
[Teamcity]: http://www.jetbrains.com/teamcity/

View File

@@ -4,11 +4,11 @@ anchor: virtualization
# Virtualization
Running your application on different environments in development and production can lead to strange bugs
popping up when you go live. It's also tricky to keep different development environments up to date with the same
version for all libraries used when working with a team of developers.
Running your application on different environments in development and production can lead to strange bugs popping up
when you go live. It's also tricky to keep different development environments up to date with the same version for all
libraries used when working with a team of developers.
If you are developing on Windows and deploying to Linux (or anything non-Windows) or are developing in a team, you
should consider using a virtual machine.
This sounds tricky, but besides the widely known virtualization environments like VMware or VirtualBox, there are
additional tools that may help you setting up a virtual environment in a few easy steps.
If you are developing on Windows and deploying to Linux (or anything non-Windows) or are developing in a team, you
should consider using a virtual machine. This sounds tricky, but besides the widely known virtualization environments
like VMware or VirtualBox, there are additional tools that may help you setting up a virtual environment in a few easy
steps.

View File

@@ -1,36 +1,37 @@
---
isChild: true
anchor: vagrant
anchor: vagrant
---
## Vagrant {#vagrant_title}
[Vagrant][vagrant] helps you building your virtual boxes on top of the known virtual environments and will configure
these environments based on a single configuration file.
These boxes can be set up manually, or you can use "provisioning"
software such as [Puppet][puppet] or [Chef][chef] to do this for you. Provisioning the base box is a great way to
ensure that multiple boxes are set up in an identical fashion and removes the need for you to maintain complicated
"set up" command lists. You can also "destroy" your base box and recreate it without many manual steps, making it
easy to create a "fresh" installation.
[Vagrant] helps you building your virtual boxes on top of the known virtual environments and will configure these
environments based on a single configuration file. These boxes can be set up manually, or you can use "provisioning"
software such as [Puppet] or [Chef] to do this for you. Provisioning the base box is a great way to ensure that
multiple boxes are set up in an identical fashion and removes the need for you to maintain complicated "set up"
command lists. You can also "destroy" your base box and recreate it without many manual steps, making it easy to create
a "fresh" installation.
Vagrant creates folders for sharing your code between your host and your virtual machine, which means that you can
Vagrant creates folders for sharing your code between your host and your virtual machine, which means that you can
create and edit your files on your host machine and then run the code inside your virtual machine.
### A little help
If you need a little help to start using Vagrant there are some services that might be useful:
- [Rove][rove]: service that allows you to pre-generate typical Vagrant builds, PHP among the options. The
provisioning is made with Chef.
- [Puphpet][puphpet]: simple GUI to set up virtual machines for PHP development. **Heavily focused in PHP**. Besides
local VMs, it can be used to deploy to cloud services as well. The provisioning is made with Puppet.
- [Protobox][protobox]: is a layer on top of vagrant and a web GUI to setup virtual machines for web development. A single YAML document controls everything that is installed on the virtual machine.
- [Phansible][phansible]: provides an easy to use interface that helps you generate Ansible Playbooks for PHP based projects.
- [Rove]: service that allows you to pre-generate typical Vagrant builds, PHP among the options. The provisioning is
made with Chef.
- [Puphpet]: simple GUI to set up virtual machines for PHP development. **Heavily focused in PHP**. Besides local VMs,
it can be used to deploy to cloud services as well. The provisioning is made with Puppet.
- [ Protobox]: is a layer on top of vagrant and a web GUI to setup virtual machines for web development. A single YAML
document controls everything that is installed on the virtual machine.
- [Phansible]: provides an easy to use interface that helps you generate Ansible Playbooks for PHP based projects.
[vagrant]: http://vagrantup.com/
[puppet]: http://www.puppetlabs.com/
[chef]: http://www.opscode.com/
[rove]: http://rove.io/
[puphpet]: https://puphpet.com/
[protobox]: http://getprotobox.com/
[phansible]: http://phansible.com/
[Vagrant]: http://vagrantup.com/
[Puppet]: http://www.puppetlabs.com/
[Chef]: http://www.opscode.com/
[Rove]: http://rove.io/
[Puphpet]: https://puphpet.com/
[Protobox]: http://getprotobox.com/
[Phansible]: http://phansible.com/

View File

@@ -1,42 +1,45 @@
---
isChild: true
anchor: docker
anchor: docker
---
## Docker {#docker_title}
Beside using Vagrant, another easy way to get a virtual development or production environment up and running is [Docker][docker].
Beside using Vagrant, another easy way to get a virtual development or production environment up and running is [Docker].
Docker helps you to provide Linux containers for all kind of applications.
There are many helpful docker images which could provide you with other great services without the need to install
these services on your local machine, e.g. MySQL or PostgreSQL and a lot more.
Have a look at the [Docker Hub Registry][docker-hub] to search a list of available pre-built containers,
which you can then run and use in very few steps.
these services on your local machine, e.g. MySQL or PostgreSQL and a lot more. Have a look at the [Docker Hub Registry]
[docker-hub] to search a list of available pre-built containers, which you can then run and use in very few steps.
### Example: Runnning your PHP Applications in Docker
After you [installed docker][docker-install] on your machine, you can start an Apache with PHP support in one step.
After you [installed docker][docker-install] on your machine, you can start an Apache with PHP support in one step.
The following command will download a fully functional Apache installation with the latest PHP version and provide the
directory `/path/to/your/php/files` at `http://localhost:8080`:
{% highlight bash %}
docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache
{% highlight console %}
docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache
{% endhighlight %}
After running `docker run` your container is initialized and running.
After running `docker run` your container is initialized and running.
If you would like to stop or start your container again, you can use the provided name attribute and simply run
`docker stop my-php-webserver` and `docker start my-php-webserver` without providing the above mentioned parameters again.
### Learn more about Docker
The commands mentioned above only show a quick way to run an Apache web server with PHP support but there are a lot more
things that you can do with Docker.
One of the most important things for PHP developers will be linking your web server to a database instance, for example.
How this could be done is well described within the [Docker User Guide][docker-doc].
`docker stop my-php-webserver` and `docker start my-php-webserver` without providing the above mentioned parameters
again.
* [Docker Website][docker]
### Learn more about Docker
The commands mentioned above only show a quick way to run an Apache web server with PHP support but there are a lot
more things that you can do with Docker. One of the most important things for PHP developers will be linking your
web server to a database instance, for example. How this could be done is well described within the [Docker User Guide]
[docker-doc].
* [Docker Website][Docker]
* [Docker Installation][docker-install]
* [Docker Images at the Docker Hub Registry][docker-hub]
* [Docker User Guide][docker-doc]
[docker]: http://docker.com/
[Docker]: http://docker.com/
[docker-hub]: https://registry.hub.docker.com/
[docker-install]: https://docs.docker.com/installation/
[docker-doc]: https://docs.docker.com/userguide/

View File

@@ -5,4 +5,4 @@ anchor: caching
# Caching {#caching_title}
PHP is pretty quick by itself, but bottlenecks can arise when you make remote connections, load files, etc.
Thankfully, there are various tools available to speed up certain parts of your application, or reduce the number of times these various time-consuming tasks need to run.
Thankfully, there are various tools available to speed up certain parts of your application, or reduce the number of times these various time-consuming tasks need to run.

View File

@@ -1,25 +1,34 @@
---
isChild: true
anchor: opcode_cache
anchor: opcode_cache
---
## Opcode Cache {#opcode_cache_title}
When a PHP file is executed, under the hood it is first compiled to opcodes and, only then, the opcodes are executed.
If a PHP file is not modified, the opcodes will always be the same. This means that the compilation step is a waste of CPU resources.
If a PHP file is not modified, the opcodes will always be the same. This means that the compilation step is a waste of
CPU resources.
This is where opcode caches come in. They prevent redundant compilation by storing opcodes in memory and reusing it on successive calls.
Setting up an opcode cache takes a matter of minutes, and your application will speed up significantly. There's really no reason not to use it.
This is where opcode caches come in. They prevent redundant compilation by storing opcodes in memory and reusing it on
successive calls. Setting up an opcode cache takes a matter of minutes, and your application will speed up
significantly. There's really no reason not to use it.
As of PHP 5.5, there is a built-in opcode cache called [OPcache][opcache-book]. It is also available for earlier versions.
As of PHP 5.5, there is a built-in opcode cache called [OPcache][opcache-book]. It is also available for earlier
versions.
Read more about opcode caches:
* [OPcache][opcache-book] (built-in since PHP 5.5)
* [APC](http://php.net/manual/en/book.apc.php) (PHP 5.4 and earlier)
* [XCache](http://xcache.lighttpd.net/)
* [Zend Optimizer+](http://www.zend.com/products/server/) (part of Zend Server package)
* [WinCache](http://www.iis.net/download/wincacheforphp) (extension for MS Windows Server)
* [list of PHP accelerators on Wikipedia](http://en.wikipedia.org/wiki/List_of_PHP_accelerators)
* [APC] (PHP 5.4 and earlier)
* [XCache]
* [Zend Optimizer+] (part of Zend Server package)
* [WinCache] (extension for MS Windows Server)
* [list of PHP accelerators on Wikipedia][PHP_accelerators]
[opcache-book]: http://php.net/manual/en/book.opcache.php
[opcache-book]: http://php.net/book.opcache
[APC]: http://php.net/book.apc
[XCache]: http://xcache.lighttpd.net/
[Zend Optimizer+]: http://www.zend.com/products/server/
[WinCache]: http://www.iis.net/download/wincacheforphp
[PHP_accelerators]: http://en.wikipedia.org/wiki/List_of_PHP_accelerators

View File

@@ -1,6 +1,6 @@
---
isChild: true
anchor: object_caching
anchor: object_caching
---
## Object Caching {#object_caching_title}
@@ -16,17 +16,17 @@ advantage of them. APCu, XCache, and WinCache all provide APIs to save data from
The most commonly used memory object caching systems are APCu and memcached. APCu is an excellent choice for object
caching, it includes a simple API for adding your own data to its memory cache and is very easy to setup and use. The
one real limitation of APCu is that it is tied to the server it's installed on. Memcached on the other hand is installed
as a separate service and can be accessed across the network, meaning that you can store objects in a hyper-fast data
store in a central location and many different systems can pull from it.
one real limitation of APCu is that it is tied to the server it's installed on. Memcached on the other hand is
installed as a separate service and can be accessed across the network, meaning that you can store objects in a
hyper-fast data store in a central location and many different systems can pull from it.
Note that when running PHP as a (Fast-)CGI application inside your webserver, every PHP process will have its own
cache, i.e. APCu data is not shared between your worker processes. In these cases, you might want to consider using
memcached instead, as it's not tied to the PHP processes.
Note that when running PHP as a (Fast-)CGI application inside your webserver, every PHP process will have its own cache,
i.e. APCu data is not shared between your worker processes. In these cases, you might want to consider using memcached
instead, as it's not tied to the PHP processes.
In a networked configuration APCu will usually outperform memcached in terms of access speed, but memcached will be able
to scale up faster and further. If you do not expect to have multiple servers running your application, or do not need
the extra features that memcached offers then APCu is probably your best choice for object caching.
In a networked configuration APCu will usually outperform memcached in terms of access speed, but memcached will be
able to scale up faster and further. If you do not expect to have multiple servers running your application, or do not
need the extra features that memcached offers then APCu is probably your best choice for object caching.
Example logic using APCu:
@@ -45,11 +45,11 @@ print_r($data);
Note that prior to PHP 5.5, APC provides both an object cache and a bytecode cache. APCu is a project to bring APC's
object cache to PHP 5.5+, since PHP now has a built-in bytecode cache (OPcache).
Learn more about popular object caching systems:
### Learn more about popular object caching systems:
* [APCu](https://github.com/krakjoe/apcu)
* [APC Functions](http://php.net/manual/en/ref.apc.php)
* [APC Functions](http://php.net/ref.apc)
* [Memcached](http://memcached.org/)
* [Redis](http://redis.io/)
* [XCache APIs](http://xcache.lighttpd.net/wiki/XcacheApi)
* [WinCache Functions](http://www.php.net/manual/en/ref.wincache.php)
* [WinCache Functions](http://php.net/ref.wincache)

View File

@@ -0,0 +1,6 @@
---
anchor: documenting
title: Documenting your Code
---
# Documenting your Code {#documenting_title}

View File

@@ -1,42 +0,0 @@
---
anchor: resources
---
# Resources {#resources_title}
## From the Source
* [PHP Website](http://php.net/)
* [PHP Documentation](http://php.net/docs.php)
## People to Follow
* [Rasmus Lerdorf](http://twitter.com/rasmus)
* [Fabien Potencier](http://twitter.com/fabpot)
* [Derick Rethans](http://twitter.com/derickr)
* [Chris Shiflett](http://twitter.com/shiflett)
* [Sebastian Bergmann](http://twitter.com/s_bergmann)
* [Matthew Weier O'Phinney](http://twitter.com/mwop)
* [Pádraic Brady](http://twitter.com/padraicb)
* [Anthony Ferrara](http://twitter.com/ircmaxell)
* [Nikita Popov](http://twitter.com/nikita_ppv)
## Mentoring
* [phpmentoring.org](http://phpmentoring.org/) - Formal, peer to peer mentoring in the PHP community.
## PHP PaaS Providers
* [PagodaBox](https://pagodabox.com/)
* [AppFog](https://appfog.com/)
* [Heroku](https://devcenter.heroku.com/categories/php)
* [fortrabbit](http://fortrabbit.com/)
* [Engine Yard Cloud](https://www.engineyard.com/products/cloud)
* [Red Hat OpenShift Platform](http://openshift.com)
* [dotCloud](http://docs.dotcloud.com/services/php/)
* [AWS Elastic Beanstalk](http://aws.amazon.com/elasticbeanstalk/)
* [cloudControl](https://www.cloudcontrol.com/)
* [Windows Azure](http://www.windowsazure.com/)
* [Zend Developer Cloud](http://www.phpcloud.com/develop)
* [Google App Engine](https://developers.google.com/appengine/docs/php/gettingstarted/)
* [Jelastic](http://jelastic.com/)

View File

@@ -1,24 +0,0 @@
---
isChild: true
anchor: frameworks
---
## Frameworks {#frameworks_title}
Rather than re-invent the wheel, many PHP developers use frameworks to build out web applications. Frameworks abstract away many of the low-level concerns and provide helpful, easy-to-use interfaces to complete common tasks.
You do not need to use a framework for every project. Sometimes plain PHP is the right way to go, but if you do need a framework then there are three main types available:
* Micro Frameworks
* Full-Stack Frameworks
* Component Frameworks
Micro-frameworks are essentially a wrapper to route a HTTP request to a callback, controller, method, etc as quickly as possible, and sometimes come with a few extra libraries to assist development such as basic database wrappers and the like. They are prominently used
to build remote HTTP services.
Many frameworks add a considerable number of features on top of what is available in a micro-framework and these are known Full-Stack
Frameworks. These often come bundled with ORMs, Authentication packages, etc.
Component-based frameworks are collections of specialized and single-purpose libraries. Disparate component-based frameworks can be used together to make a micro- or full-stack framework.
* [Popular PHP Frameworks](https://github.com/codeguy/php-the-right-way/wiki/Frameworks)

84
_posts/15-02-01-PHPDoc.md Normal file
View File

@@ -0,0 +1,84 @@
---
isChild: true
title: PHPDoc
anchor: phpdoc
---
## PHPDoc {#phpdoc_title}
PHPDoc is an informal standard for commenting PHP code. There are a *lot* of different [tags] available. The full list
of tags and examples can be found at the [PHPDoc manual].
Below is an example of how you might document a class with a few methods;
{% highlight php %}
<?php
/**
* @author A Name <a.name@example.com>
* @link http://www.phpdoc.org/docs/latest/index.html
* @package helper
*/
class DateTimeHelper
{
/**
* @param mixed $anything Anything that we can convert to a \DateTime object
*
* @return \DateTime
* @throws \InvalidArgumentException
*/
public function dateTimeFromAnything($anything)
{
$type = gettype($anything);
switch ($type) {
// Some code that tries to return a \DateTime object
}
throw new \InvalidArgumentException(
"Failed Converting param of type '{$type}' to DateTime object"
);
}
/**
* @param mixed $date Anything that we can convert to a \DateTime object
*
* @return void
*/
public function printISO8601Date($date)
{
echo $this->dateTimeFromAnything($date)->format('c');
}
/**
* @param mixed $date Anything that we can convert to a \DateTime object
*/
public function printRFC2822Date($date)
{
echo $this->dateTimeFromAnything($date)->format('r');
}
}
{% endhighlight %}
The documentation for the class as a whole firstly has the [@author] tag, this tag is used to document the author of
the code and can be repeated for documenting several authors. Secondly is the [@link] tag, used to link to a website
indicating a relationship between the website and the code. Thirdly it has the [@package] tag, used to categorize the
code.
Inside the class, the first method has an [@param] tag documenting the type, name and description of the parameter
being passed to the method. Additionally it has the [@return] and [@throws] tags for documenting the return type, and
any exceptions that could be throw respectively.
The second and third methods are very similar and have a single [@param] tag as did the first method. The import
difference between the second and third method is doc block is the inclusion/exclusion of the [@return] tag.
`@return void` explicitly informs us that there is no return, historically omitting the `@return void` statement also
results in the same (no return) action.
[tags]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/index.html
[PHPDoc manual]: http://www.phpdoc.org/docs/latest/index.html
[@author]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/author.html
[@link]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/link.html
[@package]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/package.html
[@param]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/param.html
[@return]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/return.html
[@throws]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/throws.html

View File

@@ -1,37 +0,0 @@
---
isChild: true
anchor: components
---
## Components {#components_title}
As mentioned above "Components" are another approach to the common goal of creating, distributing and implementing shared code. Various
component repositories exist, the main two of which are:
* [Packagist](/#composer_and_packagist)
* [PEAR](/#pear)
Both of these repositories have command line tools associated with them to help the installation and upgrade
processes, and have been explained in more detail in the [Dependency Management] section.
There are also component-based frameworks and component-vendors that offer no framework at all. These projects provide
another source of packages which ideally have little to no dependencies on other packages, or specific frameworks.
For example, you can use the [FuelPHP Validation package], without needing to use the FuelPHP framework
itself.
[Dependency Management]: /#dependency_management
[FuelPHP Validation package]: https://github.com/fuelphp/validation
* [Aura](http://auraphp.github.com/)
* [FuelPHP](https://github.com/fuelphp)
* [Hoa Project](https://github.com/hoaproject)
* [Orno](https://github.com/orno)
* [Symfony Components](http://symfony.com/doc/current/components/index.html)
* [The League of Extraordinary Packages](http://thephpleague.com/)
* Laravel's Illuminate Components
* [Eloquent ORM](https://github.com/illuminate/database)
* [Queue](https://github.com/illuminate/queue)
_Laravel's [Illuminate components](https://github.com/illuminate) will become better decoupled from the Laravel framework.
For now, only the components best decoupled from the Laravel framework are listed above._

View File

@@ -1,30 +0,0 @@
---
isChild: true
anchor: books
---
## Books {#books_title}
There are a lot of books around for PHP but some are sadly now quite old and no
longer contain accurate information. There are even books published for "PHP 6"
which does not exist, and will not now ever exist. The next major version of PHP
will be named "PHP 7" because of those books.
This section aims to be a living document for recommended books on PHP
development in general. If you would like your book to be added, send a PR and
it will be reviewed for relevancy.
### Free Books
* [PHP The Right Way](https://leanpub.com/phptherightway/) - This website is
available as a book completely for free
### Paid Books
* [Modernizing Legacy Applications In PHP](https://leanpub.com/mlaphp) - Get
your code under control in a series of small, specific steps
* [Building Secure PHP Apps](https://leanpub.com/buildingsecurephpapps) - Learn the security basics that a senior developer usually acquires over years of experience, all condensed down into one quick and easy handbook
* [The Grumpy Programmer's Guide To Building Testable PHP Applications](https://leanpub.com/grumpy-testing) - Learning to write testable doesn't have to suck
* [Securing PHP: Core Concepts](https://leanpub.com/securingphp-coreconcepts) - A guide to some of the most common security terms and provides some examples of them in every day PHP
* [Scaling PHP](https://leanpub.com/scalingphp) - Stop playing sysadmin and get back to coding
* [Signaling PHP](https://leanpub.com/signalingphp) - PCNLT signals are a great help when writing PHP scripts that run from the command line.

View File

@@ -1,32 +0,0 @@
---
anchor: community
---
# Community {#community_title}
The PHP community is as diverse as it is large, and its members are ready and willing to support new PHP programmers. Consider joining your local PHP user group (PUG) or attending larger PHP conferences to learn more about the best practices shown here. You can hang out on IRC in the #phpc channel on [irc.freenode.com][php-irc] and follow the [@phpc][phpc-twitter] twitter account. Get out there, meet new developers, learn new topics, and above all, make new friends! Other community resources include the Google+ PHP [Programmer community][php-programmers-gplus] and [StackOverflow][php-so].
[Read the Official PHP Events Calendar][php-calendar]
## PHP User Groups
If you live in a larger city, odds are there's a PHP user group nearby. Although there's not yet an official list of PUGs, you can easily find your local PUG by searching on [Google][google], [Meetup.com][meetup] or [PHP.ug][php-ug]. If you live in a smaller town, there may not be a local PUG; if that's the case, start one!
[Read about User Groups on the PHP Wiki][php-wiki]
## PHP Conferences
The PHP community also hosts larger regional and national conferences in many countries around the world. Well-known members of the PHP community usually speak at these larger events, so it's a great opportunity to learn directly from industry leaders.
[Find a PHP Conference][php-conf]
[php-calendar]: http://www.php.net/cal.php
[google]: https://www.google.com/search?q=php+user+group+near+me
[meetup]: http://www.meetup.com/find/
[php-ug]: http://php.ug
[php-wiki]: https://wiki.php.net/usergroups
[php-conf]: http://php.net/conferences/index.php
[phpc-twitter]: https://twitter.com/phpc
[php-programmers-gplus]: https://plus.google.com/u/0/communities/104245651975268426012
[php-irc]: http://webchat.freenode.net/?channels=phpc
[php-so]: http://stackoverflow.com/questions/tagged/php

View File

@@ -0,0 +1,5 @@
---
anchor: resources
---
# Resources {#resources_title}

View File

@@ -0,0 +1,9 @@
---
isChild: true
anchor: from_the_source
---
## From the Source {#from_the_source_title}
* [PHP Website](http://php.net/)
* [PHP Documentation](http://php.net/docs.php)

View File

@@ -0,0 +1,16 @@
---
isChild: true
anchor: people_to_follow
---
## People to Follow {#people_to_follow_title}
* [Rasmus Lerdorf](http://twitter.com/rasmus)
* [Fabien Potencier](http://twitter.com/fabpot)
* [Derick Rethans](http://twitter.com/derickr)
* [Chris Shiflett](http://twitter.com/shiflett)
* [Sebastian Bergmann](http://twitter.com/s_bergmann)
* [Matthew Weier O'Phinney](http://twitter.com/mwop)
* [Pádraic Brady](http://twitter.com/padraicb)
* [Anthony Ferrara](http://twitter.com/ircmaxell)
* [Nikita Popov](http://twitter.com/nikita_ppv)

View File

@@ -0,0 +1,8 @@
---
isChild: true
anchor: mentoring
---
## Mentoring {#mentoring_title}
* [phpmentoring.org](http://phpmentoring.org/) - Formal, peer to peer mentoring in the PHP community.

View File

@@ -0,0 +1,19 @@
---
isChild: true
anchor: php_paas_providers
---
## PHP PaaS Providers {#php_paas_providers_title}
* [PagodaBox](https://pagodabox.com/)
* [AppFog](https://appfog.com/)
* [Heroku](https://devcenter.heroku.com/categories/php)
* [fortrabbit](http://fortrabbit.com/)
* [Engine Yard Cloud](https://www.engineyard.com/products/cloud)
* [Red Hat OpenShift Platform](http://openshift.com)
* [dotCloud](http://docs.dotcloud.com/services/php/)
* [AWS Elastic Beanstalk](http://aws.amazon.com/elasticbeanstalk/)
* [cloudControl](https://www.cloudcontrol.com/)
* [Windows Azure](http://www.windowsazure.com/)
* [Google App Engine](https://developers.google.com/appengine/docs/php/gettingstarted/)
* [Jelastic](http://jelastic.com/)

View File

@@ -0,0 +1,28 @@
---
isChild: true
anchor: frameworks
---
## Frameworks {#frameworks_title}
Rather than re-invent the wheel, many PHP developers use frameworks to build out web applications. Frameworks abstract
away many of the low-level concerns and provide helpful, easy-to-use interfaces to complete common tasks.
You do not need to use a framework for every project. Sometimes plain PHP is the right way to go, but if you do need a
framework then there are three main types available:
* Micro Frameworks
* Full-Stack Frameworks
* Component Frameworks
Micro-frameworks are essentially a wrapper to route a HTTP request to a callback, controller, method, etc as quickly as
possible, and sometimes come with a few extra libraries to assist development such as basic database wrappers and the
like. They are prominently used to build remote HTTP services.
Many frameworks add a considerable number of features on top of what is available in a micro-framework and these are
known Full-Stack Frameworks. These often come bundled with ORMs, Authentication packages, etc.
Component-based frameworks are collections of specialized and single-purpose libraries. Disparate component-based
frameworks can be used together to make a micro- or full-stack framework.
* [Popular PHP Frameworks](https://github.com/codeguy/php-the-right-way/wiki/Frameworks)

View File

@@ -0,0 +1,48 @@
---
isChild: true
anchor: components
---
## Components {#components_title}
As mentioned above "Components" are another approach to the common goal of creating, distributing and implementing
shared code. Various component repositories exist, the main two of which are:
* [Packagist]
* [PEAR]
Both of these repositories have command line tools associated with them to help the installation and upgrade processes,
and have been explained in more detail in the [Dependency Management] section.
There are also component-based frameworks and component-vendors that offer no framework at all. These projects provide
another source of packages which ideally have little to no dependencies on other packages, or specific frameworks.
For example, you can use the [FuelPHP Validation package], without needing to use the FuelPHP framework itself.
* [Aura]
* [FuelPHP]
* [Hoa Project]
* [Orno]
* [Symfony Components]
* [The League of Extraordinary Packages]
* Laravel's Illuminate Components
* [Eloquent ORM]
* [Queue]
_Laravel's [Illuminate components] will become better decoupled from the Laravel framework. For now, only the
components best decoupled from the Laravel framework are listed above._
[Packagist]: /#composer_and_packagist
[PEAR]: /#pear
[Dependency Management]: /#dependency_management
[FuelPHP Validation package]: https://github.com/fuelphp/validation
[Aura]: http://auraphp.com/packages/v2
[FuelPHP]: https://github.com/fuelphp
[Hoa Project]: https://github.com/hoaproject
[Orno]: https://github.com/orno
[Symfony Components]: http://symfony.com/doc/current/components/index.html
[The League of Extraordinary Packages]: http://thephpleague.com/
[Eloquent ORM]: https://github.com/illuminate/database
[Queue]: https://github.com/illuminate/queue
[Illuminate components]: https://github.com/illuminate

31
_posts/16-08-01-Books.md Normal file
View File

@@ -0,0 +1,31 @@
---
isChild: true
anchor: books
---
## Books {#books_title}
There are a lot of books around for PHP but some are sadly now quite old and no longer contain accurate information.
There are even books published for "PHP 6" which does not exist, and will not now ever exist. The next major version of
PHP will be named "PHP 7" because of those books.
This section aims to be a living document for recommended books on PHP development in general. If you would like your
book to be added, send a PR and it will be reviewed for relevancy.
### Free Books
* [PHP The Right Way](https://leanpub.com/phptherightway/) - This website is available as a book completely for free.
### Paid Books
* [Modernizing Legacy Applications In PHP](https://leanpub.com/mlaphp) - Get your code under control in a series of
small, specific steps
* [Building Secure PHP Apps](https://leanpub.com/buildingsecurephpapps) - Learn the security basics that a senior
developer usually acquires over years of experience, all condensed down into one quick and easy handbook
* [The Grumpy Programmer's Guide To Building Testable PHP Applications](https://leanpub.com/grumpy-testing) - Learning
to write testable doesn't have to suck
* [Securing PHP: Core Concepts](https://leanpub.com/securingphp- coreconcepts) - A guide to some of the most common
security terms and provides some examples of them in every day PHP
* [Scaling PHP]( https:// leanpub.com/scalingphp) - Stop playing sysadmin and get back to coding
* [Signaling PHP]( https:// leanpub.com/ signalingphp) - PCNLT signals are a great help when writing PHP scripts that
run from the command line.

View File

@@ -0,0 +1,21 @@
---
anchor: community
---
# Community {#community_title}
The PHP community is as diverse as it is large, and its members are ready and willing to support new PHP programmers.
Consider joining your local PHP user group (PUG) or attending larger PHP conferences to learn more about the best
practices shown here. You can hang out on IRC in the #phpc channel on [irc.freenode.com][php-irc] and follow the
[@phpc][phpc-twitter] twitter account. Get out there, meet new developers, learn new topics, and above all, make new
friends! Other community resources include the Google+ PHP [Programmer community][php-programmers-gplus] and
[StackOverflow][php-so].
[Read the Official PHP Events Calendar][php-calendar]
[php-irc]: http://webchat.freenode.net/?channels=phpc
[phpc-twitter]: https://twitter.com/phpc
[php-programmers-gplus]: https://plus.google.com/u/0/communities/104245651975268426012
[php-so]: http://stackoverflow.com/questions/tagged/php
[php-calendar]: http://php.net/cal.php

View File

@@ -1,63 +0,0 @@
---
anchor: phpdoc
---
# PHPDoc {#phpdoc}
PHPDoc is an informal standard for commenting PHP code. There are a *lot* of different [tags](http://www.phpdoc.org/docs/latest/references/phpdoc/tags/index.html) available. The full list of tags and examples can be found at the [PHPDoc manual](http://www.phpdoc.org/docs/latest/index.html).
Below is an example of how you might document a class with a few methods;
{% highlight php %}
<?php
/**
* @author A Name <a.name@example.com>
* @link http://www.phpdoc.org/docs/latest/index.html
* @package helper
*/
class DateTimeHelper
{
/**
* @param mixed $anything Anything that we can convert to a \DateTime object
*
* @return \DateTime
* @throws \InvalidArgumentException
*/
public function dateTimeFromAnything($anything)
{
$type = gettype($anything);
switch ($type) {
// Some code that tries to return a \DateTime object
}
throw new \InvalidArgumentException(
"Failed Converting param of type '{$type}' to DateTime object"
);
}
/**
* @param mixed $date Anything that we can convert to a \DateTime object
*
* @return void
*/
public function printISO8601Date($date)
{
echo $this->dateTimeFromAnything($date)->format('c');
}
/**
* @param mixed $date Anything that we can convert to a \DateTime object
*/
public function printRFC2822Date($date)
{
echo $this->dateTimeFromAnything($date)->format('r');
}
}
{% endhighlight %}
The documentation for the class as a whole firstly has the [@author](http://www.phpdoc.org/docs/latest/references/phpdoc/tags/author.html) tag, this tag is used to document the author of the code and can be repeated for documenting several authors. Secondly is the [@link](http://www.phpdoc.org/docs/latest/references/phpdoc/tags/link.html) tag, used to link to a website indicating a relationship between the website and the code. Thirdly it has the [@package](http://www.phpdoc.org/docs/latest/references/phpdoc/tags/package.html) tag, used to categorize the code.
Inside the class, the first method has an [@param](http://www.phpdoc.org/docs/latest/references/phpdoc/tags/param.html) tag documenting the type, name and description of the parameter being passed to the method. Additionally it has the [@return](http://www.phpdoc.org/docs/latest/references/phpdoc/tags/return.html) and [@throws](http://www.phpdoc.org/docs/latest/references/phpdoc/tags/throws.html) tags for documenting the return type, and any exceptions that could be throw respectively.
The second and third methods are very similar and have a single [@param](http://www.phpdoc.org/docs/latest/references/phpdoc/tags/param.html) tag as did the first method. The import difference between the second and third method is doc block is the inclusion/exclusion of the [@return](http://www.phpdoc.org/docs/latest/references/phpdoc/tags/return.html) tag. `@return void` explicitly informs us that there is no return, historically omitting the `@return void` statement also results in the same (no return) action.

View File

@@ -0,0 +1,25 @@
---
isChild: true
anchor: user_groups
---
## PHP User Groups {#user_groups_title}
If you live in a larger city, odds are there's a PHP user group nearby. Although there's not yet an official list of
PUGs, you can easily find your local PUG by searching on [Google][google], [Meetup.com][meetup] or [PHP.ug][php-ug]. If
you live in a smaller town, there may not be a local PUG; if that's the case, start one!
Special mention should be made of two global user groups: [NomadPHP] and [PHPWomen]. [NomadPHP] offers twice monthly
online user group meetings with presentations by some of the top speakers in the PHP community.
[PHPWomen] is a non-exclusive user group originally targeted towards the women in the PHP world. Membership is open to
everyone who supports a more diverse community. PHPWomen provide a network for support, mentorship and education, and
generally promote the creating of a "female friendly" and professional atmosphere.
[Read about User Groups on the PHP Wiki][php-wiki]
[google]: https://www.google.com/search?q=php+user+group+near+me
[meetup]: http://www.meetup.com/find/
[php-ug]: http://php.ug/
[NomadPHP]: https://nomadphp.com/
[PHPWomen]: http://phpwomen.org/
[php-wiki]: https://wiki.php.net/usergroups

View File

@@ -0,0 +1,15 @@
---
isChild: true
anchor: conferences
---
## PHP Conferences {#conferences_title}
The PHP community also hosts larger regional and national conferences in many countries around the world. Well-known
members of the PHP community usually speak at these larger events, so it's a great opportunity to learn directly from
industry leaders.
[Find a PHP Conference][php-conf]
[php-conf]: http://php.net/conferences/index.php

View File

@@ -1,13 +1,13 @@
---
layout: page
title: Design Patterns
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
@@ -134,30 +134,37 @@ var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)
The code above implements the singleton pattern using a [*static* variable](http://php.net/language.variables.scope#language.variables.scope.static) and the static creation method `getInstance()`.
Note the following:
* The constructor [`__construct`](http://php.net/language.oop5.decon#object.construct) is declared as protected to prevent creating a new instance outside of the class via the `new` operator.
* The magic method [`__clone`](http://php.net/language.oop5.cloning#object.clone) is declared as private to prevent cloning of an instance of the class via the [`clone`](http://php.net/language.oop5.cloning) operator.
* The magic method [`__wakeup`](http://php.net/language.oop5.magic#object.wakeup) is declared as private to prevent unserializing of an instance of the class via the global function [`unserialize()`](http://php.net/function.unserialize).
* A new instance is created via [late static binding](http://php.net/language.oop5.late-static-bindings) in the static creation method `getInstance()` with the keyword `static`. This allows the subclassing of the class `Singleton` in the example.
* The constructor [`__construct()`](http://php.net/language.oop5.decon#object.construct) is declared as protected to
prevent creating a new instance outside of the class via the `new` operator.
* The magic method [`__clone()`](http://php.net/language.oop5.cloning#object.clone) is declared as private to prevent
cloning of an instance of the class via the [`clone`](http://php.net/language.oop5.cloning) operator.
* The magic method [`__wakeup()`](http://php.net/language.oop5.magic#object.wakeup) is declared as private to prevent
unserializing of an instance of the class via the global function [`unserialize()`](http://php.net/function.unserialize)
.
* A new instance is created via [late static binding](http://php.net/language.oop5.late-static-bindings) in the static
creation method `getInstance()` with the keyword `static`. This allows the subclassing of the class `Singleton` in the
example.
The singleton pattern is useful when we need to make sure we only have a single instance of a class for the entire
request lifecycle in a web application. This typically occurs when we have global objects (such as a Configuration
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)
## 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:
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:
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
@@ -191,19 +198,19 @@ class ArrayOutput implements OutputInterface
}
{% endhighlight %}
By encapsulating the above algorithms you are making it nice and clear in your code that other developers can easily
By encapsulating the above algorithms you are making it nice and clear in your code that other developers can easily
add new output types without affecting the client code.
You will see how each concrete 'output' class implements an OutputInterface - this serves two purposes, primarily it
provides a simple contract which must be obeyed by any new concrete implementations. Secondly by implementing a common
interface you will see in the next section that you can now utilise [Type Hinting](http://php.net/manual/en/language.oop5.typehinting.php) to ensure that the client which is utilising these behaviours is of the correct type in
interface you will see in the next section that you can now utilise [Type Hinting](http://php.net/language.oop5.typehinting) to ensure that the client which is utilising these behaviours is of the correct type in
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
{
private $output;
@@ -223,9 +230,9 @@ 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();
// Want an array?
@@ -251,7 +258,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

@@ -1,23 +1,23 @@
---
layout: page
title: Functional Programming in PHP
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`
The most common usage of higher-order functions is when implementing a strategy pattern. The built-in `array_filter()`
function asks both for the input array (data) and a function (a strategy or a callback) used as a filter function on
each array item.
@@ -42,11 +42,11 @@ print_r($output);
{% endhighlight %}
A closure is an anonymous function that can access variables imported from the outside scope without using any global
variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is
variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is
defined. Closures can work around variable scope restrictions in a clean way.
In the next example we use closures to define a function returning a single filter function for `array_filter`, out of
a family of filter functions.
In the next example we use closures to define a function returning a single filter function for `array_filter()`, out
of a family of filter functions.
{% highlight php %}
<?php
@@ -70,18 +70,19 @@ $output = array_filter($input, criteria_greater_than(3));
print_r($output); // items > 3
{% endhighlight %}
Each filter function in the family accepts only elements greater than some minimum value. Single filter returned by
`criteria_greater_than` is a closure with `$min` argument closed by the value in the scope (given as an argument when
Each filter function in the family accepts only elements greater than some minimum value. Single filter returned by
`criteria_greater_than` is a closure with `$min` argument closed by the value in the scope (given as an argument when
`criteria_greater_than` is called).
Early binding is used by default for importing `$min` variable into the created function. For true closures with late
binding one should use a reference when importing. Imagine a templating or input validation library, where closure is
binding one should use a reference when importing. Imagine a templating or input validation library, where closure is
defined to capture variables in scope and access them later when the anonymous function is evaluated.
* [Read about Anonymous functions][anonymous-functions]
* [More details in the Closures RFC][closures-rfc]
* [Read about dynamically invoking functions with `call_user_func_array`][call-user-func-array]
* [Read about dynamically invoking functions with `call_user_func_array()`][call-user-func-array]
[anonymous-functions]: http://www.php.net/manual/en/functions.anonymous.php
[call-user-func-array]: http://php.net/manual/en/function.call-user-func-array.php
[anonymous-functions]: http://php.net/functions.anonymous
[closures-rfc]: https://wiki.php.net/rfc/closures
[call-user-func-array]: http://php.net/function.call-user-func-array

View File

@@ -1,6 +1,6 @@
---
layout: page
title: The Basics
title: The Basics
---
# The Basics
@@ -33,8 +33,8 @@ if (strpos('testing', 'test') !== false) { // true, as strict comparison was
}
{% endhighlight %}
* [Comparison operators](http://php.net/manual/en/language.operators.comparison.php)
* [Comparison table](http://php.net/manual/en/types.comparisons.php)
* [Comparison operators](http://php.net/language.operators.comparison)
* [Comparison table](http://php.net/types.comparisons)
## Conditional statements
@@ -66,7 +66,7 @@ function test($a)
}
{% endhighlight %}
* [If statements](http://php.net/manual/en/control-structures.if.php)
* [If statements](http://php.net/control-structures.if)
### Switch statements
@@ -99,13 +99,13 @@ function test($a)
}
{% endhighlight %}
* [Switch statements](http://php.net/manual/en/control-structures.switch.php)
* [Switch statements](http://php.net/control-structures.switch)
* [PHP switch](http://phpswitch.com/)
## 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
@@ -124,8 +124,8 @@ function array()
}
{% endhighlight %}
* [Global space](http://php.net/manual/en/language.namespaces.global.php)
* [Global rules](http://php.net/manual/en/userlandnaming.rules.php)
* [Global space](http://php.net/language.namespaces.global)
* [Global rules](http://php.net/userlandnaming.rules)
## Strings
@@ -149,21 +149,21 @@ $a = 'Multi-line example' // concatenation operator (.)
. 'of what to do';
{% endhighlight %}
* [String Operators](http://php.net/manual/en/language.operators.string.php)
* [String Operators](http://php.net/language.operators.string)
### 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 %}
@@ -177,12 +177,12 @@ echo 'This is my string, look at how pretty it is.'; // no need to parse a si
*/
{% endhighlight %}
* [Single quote](http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single)
* [Single quote](http://php.net/language.types.string#language.types.string.syntax.single)
#### Double quotes
Double quotes are the Swiss Army Knife of strings. They will not only parse variables as mentioned above, but all sorts
of special characters, like `\n` for newline, `\t` for a tab, etc.
of special characters, like `\n` for newline, `\t` for a tab, etc.
{% highlight php %}
<?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.
@@ -227,7 +227,7 @@ $juice = array('apple', 'orange', 'plum');
echo "I drank some juice made of {$juice[1]}s"; // $juice[1] will be parsed
{% endhighlight %}
* [Double quotes](http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double)
* [Double quotes](http://php.net/language.types.string#language.types.string.syntax.double)
#### Nowdoc syntax
@@ -253,7 +253,7 @@ EOD; // closing 'EOD' must be on it's own line, and to th
*/
{% endhighlight %}
* [Nowdoc syntax](http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc)
* [Nowdoc syntax](http://php.net/language.types.string#language.types.string.syntax.nowdoc)
#### Heredoc syntax
@@ -281,25 +281,25 @@ EOD; // closing 'EOD' must be on it's own line, and to th
*/
{% endhighlight %}
* [Heredoc syntax](http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc)
* [Heredoc syntax](http://php.net/language.types.string#language.types.string.syntax.heredoc)
### 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
@@ -361,12 +363,13 @@ return ($a == 3) ? "yay" : "nope"; // return yay or nope if $a == 3
// vs
<?php
$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
@@ -380,14 +383,13 @@ Another example is the snippet below which will return true if ($a != 3 AND $b !
return ($a != 3 && $b != 4) || $c == 5;
{% endhighlight %}
* [Ternary operators](http://php.net/manual/en/language.operators.comparison.php)
* [Ternary operators](http://php.net/language.operators.comparison)
## 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