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 3. Wrap all text to 120 characters
4. Code samples should adhere to PSR-1 or higher 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 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

@@ -6,7 +6,10 @@ anchor: use_the_current_stable_version
## Use the Current Stable Version (5.6) {#use_the_current_stable_version_title} ## 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-release]: http://php.net/downloads.php
[php-docs]: http://www.php.net/manual/en/ [php-docs]: http://php.net/manual/

View File

@@ -6,10 +6,14 @@ anchor: builtin_web_server
## Built-in web server {#builtin_web_server_title} ## 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] * [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

@@ -5,40 +5,42 @@ 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 OS X comes prepackaged with PHP but it is normally a little behind the latest stable. Mountain Lion has 5.3.10,
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. 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. There are multiple ways to install PHP on OS X.
### Install PHP via Homebrew ### Install PHP via Homebrew
[Homebrew](http://brew.sh/) is a powerful package manager for OS X, which can help you install PHP and [Homebrew] is a powerful package manager for OS X, which can help you install PHP and various extensions easily.
various extensions easily. [Homebrew PHP] is a repository that contains PHP-related "formulae" for Homebrew, [Homebrew PHP] is a repository that contains PHP-related "formulae" for Homebrew, and will let you install PHP.
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 ### Install PHP via phpbrew
[phpbrew] is a tool for installing and managing multiple PHP versions. This can be really useful if two [phpbrew] is a tool for installing and managing multiple PHP versions. This can be really useful if two different
different applications/projects require different versions of PHP, and you are not using virtual machines. applications/projects require different versions of PHP, and you are not using virtual machines.
### Compile from Source ### Compile from Source
Another option that gives you control over the version of PHP you install, is to [compile it yourself][mac-compile]. 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"] In that case be sure to have installed either [Xcode][xcode-gcc-substitution] or Apple's substitute
downloadable from Apple's Mac Developer Center. ["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]: http://brew.sh/
[Homebrew PHP]: https://github.com/Homebrew/homebrew-php#installation [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 [xcode-gcc-substitution]: https://github.com/kennethreitz/osx-gcc-installer
["Command Line Tools for XCode"]: https://developer.apple.com/downloads ["Command Line Tools for XCode"]: https://developer.apple.com/downloads
[mamp-downloads]: http://www.mamp.info/en/downloads/ [mamp-downloads]: http://www.mamp.info/en/downloads/
[phpbrew]: https://github.com/phpbrew/phpbrew
[xampp]: http://www.apachefriends.org/en/xampp.html [xampp]: http://www.apachefriends.org/en/xampp.html

View File

@@ -5,24 +5,26 @@ anchor: windows_setup
## Windows Setup {#windows_setup_title} ## 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' PHP is available in several ways for Windows. You can [download the binaries][php-downloads] and until recently you
installer. The installer is no longer supported and stops at PHP 5.3.0. 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 For learning and local development you can use the built in webserver with PHP 5.4+ so you don't need to worry about
would like an "all-in-one" which includes a full-blown webserver and MySQL too then tools such as the [Web Platform Installer][wpi], configuring it. If you would like an "all-in-one" which includes a full-blown webserver and MySQL too then tools such
[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 as the [Web Platform Installer][wpi], [Zend Server CE][zsce], [XAMPP][xampp], [EasyPHP][easyphp] and [WAMP][wamp] will
a little different from production so be careful of environment differences if you are working on Windows and deploying to Linux. 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 [php-downloads]: http://windows.php.net
[phpmanager]: http://phpmanager.codeplex.com/
[wpi]: http://www.microsoft.com/web/downloads/platform.aspx [wpi]: http://www.microsoft.com/web/downloads/platform.aspx
[zsce]: http://www.zend.com/en/products/server-ce/ [zsce]: http://www.zend.com/en/products/server-ce/
[xampp]: http://www.apachefriends.org/en/xampp.html [xampp]: http://www.apachefriends.org/en/xampp.html
[easyphp]: http://www.easyphp.org/ [easyphp]: http://www.easyphp.org/
[wamp]: http://www.wampserver.com/en/ [wamp]: http://www.wampserver.com/en/
[phpmanager]: http://phpmanager.codeplex.com/
[php-iis]: http://php.iis.net/ [php-iis]: http://php.iis.net/

View File

@@ -10,13 +10,14 @@ PHP developers to choose several of these and combine them into a single project
their projects. their projects.
The [Framework Interop Group][fig] has proposed and approved a series of style recommendations. Not all of them related 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 to code-style, but those that do are [PSR-0][psr0], [PSR-1][psr1], [PSR-2][psr2] and [PSR-4][psr4]. These
are merely a set of rules that some projects like Drupal, Zend, Symfony, CakePHP, phpBB, AWS SDK, FuelPHP, Lithium, recommendations are merely a set of rules that some projects like Drupal, Zend, Symfony, CakePHP, phpBB, AWS SDK,
etc are starting to adopt. You can use them for your own projects, or continue to use your own personal style. 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 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, of the coding standards made by PEAR or Zend. This means other developers can easily read and work with your code, and
and applications that implement the components can have consistency even when working with lots of third-party code. 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-0][psr0]
* [Read about PSR-1][psr1] * [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 Zend Coding Standards][zend-cs]
* [Read about Symfony Coding Standards][symfony-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 You can use [PHP_CodeSniffer][phpcs] to check code against any one of these recommendations, and plugins for text
like [Sublime Text 2][st-cs] to be given real time feedback. 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 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 [PHP Coding Standards Fixer][phpcsfixer] which has a very well tested codebase. It is bigger and slower, but very
and used by some huge projects like Magento and Symfony. Another option is [php.tools][phptools], which is made popular stable and used by some huge projects like Magento and Symfony. Another option is [php.tools][phptools], which is made
by the [sublime-phpfmt][sublime-phpfmt] editor plugin. While being newer, it makes great improvements in performance, popular by the [sublime-phpfmt][sublime-phpfmt] editor plugin. While being newer, it makes great improvements in
meaning real-time editor fixing is more fluid. 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/ [fig]: http://www.php-fig.org/
[psr0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md [psr0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

View File

@@ -6,8 +6,8 @@ anchor: programming_paradigms
## Programming Paradigms {#programming_paradigms_title} ## Programming Paradigms {#programming_paradigms_title}
PHP is a flexible, dynamic language that supports a variety of programming techniques. It has evolved dramatically over 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 the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in
(2009), and traits in PHP 5.4 (2012). PHP 5.3 (2009), and traits in PHP 5.4 (2012).
### Object-oriented Programming ### Object-oriented Programming
@@ -19,12 +19,12 @@ interfaces, inheritance, constructors, cloning, exceptions, and more.
### Functional Programming ### Functional Programming
PHP supports first-class function, meaning that a function can be assigned to a variable. Both user-defined and built-in PHP supports first-class function, meaning that a function can be assigned to a variable. Both user-defined and
functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to other built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to
functions (feature called Higher-order functions) and function can return other functions. 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 Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code
on iteration. focus on iteration.
New anonymous functions (with support for closures) are present since PHP 5.3 (2009). 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] * [Read about the Closure class][closure-class]
* [More details in the Closures RFC][closures-rfc] * [More details in the Closures RFC][closures-rfc]
* [Read about Callables][callables] * [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 ### Meta Programming
@@ -47,15 +47,17 @@ available as `__call()` and `__callStatic()`.
* [Read about Magic Methods][magic-methods] * [Read about Magic Methods][magic-methods]
* [Read about Reflection][reflection] * [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://php.net/language.oop5
[oop]: http://www.php.net/manual/en/language.oop5.php [traits]: http://php.net/language.oop5.traits
[anonymous-functions]: http://www.php.net/manual/en/functions.anonymous.php [anonymous-functions]: http://php.net/functions.anonymous
[closure-class]: http://php.net/manual/en/class.closure.php [closure-class]: http://php.net/class.closure
[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
[closures-rfc]: https://wiki.php.net/rfc/closures [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

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

@@ -6,8 +6,11 @@ anchor: standard_php_library
## Standard PHP Library {#standard_php_library_title} ## 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] * [Read about the SPL][spl]
[spl]: http://php.net/manual/en/book.spl.php
[spl]: http://php.net/book.spl

View File

@@ -5,19 +5,22 @@ anchor: command_line_interface
## Command Line Interface {#command_line_interface_title} ## 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: Try running PHP from your command line:
{% highlight bash %} {% highlight console %}
> php -i > php -i
{% endhighlight %} {% 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. 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"; echo "Hello, $name\n";
{% endhighlight %} {% 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: To run our script, above, from the command line:
{% highlight bash %} {% highlight console %}
> php hello.php > php hello.php
Usage: php hello.php [name] Usage: php hello.php [name]
> php hello.php world > php hello.php world
@@ -48,10 +54,11 @@ Hello, world
* [Learn about running PHP from the command line][php-cli] * [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] * [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 [phpinfo]: http://php.net/function.phpinfo
[argc]: http://php.net/manual/en/reserved.variables.argc.php [cli-options]: http://php.net/features.commandline.options
[argv]: http://php.net/manual/en/reserved.variables.argv.php [argc]: http://php.net/reserved.variables.argc
[php-cli]: http://php.net/manual/en/features.commandline.php [argv]: http://php.net/reserved.variables.argv
[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
[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

@@ -8,20 +8,22 @@ anchor: xdebug
One of the most useful tools in software development is a proper debugger. It allows you to trace the execution of your 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 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 Breakpoints and stack inspection. It can also allow tools like PHPUnit and KCacheGrind to perform code coverage
and code profiling. 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 If you find yourself in a bind, willing to resort to `var_dump()`/`print_r()`, and you still can't find the solution -
need to use the debugger. 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 [Installing XDebug][xdebug-install] can be tricky, but one of its most important features is "Remote Debugging" - if
develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you will you develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you
want to enable right away. will want to enable right away.
Traditionally, you will modify your Apache VHost or .htaccess file with these values: Traditionally, you will modify your Apache VHost or .htaccess file with these values:
php_value xdebug.remote_host=192.168.?.? {% highlight ini %}
php_value xdebug.remote_port=9000 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 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: listen on. Then it's just a matter of putting your IDE into "listen for connections" mode, and loading the URL:
@@ -38,6 +40,7 @@ stand-alone xdebug GUI for Mac.
* [Learn more about XDebug][xdebug-docs] * [Learn more about XDebug][xdebug-docs]
* [Learn more about MacGDBp][macgdbp-install] * [Learn more about MacGDBp][macgdbp-install]
[xdebug-docs]: http://xdebug.org/docs/
[xdebug-install]: http://xdebug.org/docs/install [xdebug-install]: http://xdebug.org/docs/install
[xdebug-docs]: http://xdebug.org/docs/
[macgdbp-install]: http://www.bluestatic.org/software/macgdbp/ [macgdbp-install]: http://www.bluestatic.org/software/macgdbp/

View File

@@ -4,11 +4,16 @@ anchor: dependency_management
# Dependency Management {#dependency_management_title} # 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 **Composer** when managing dependencies for a single project.
* Use **PEAR** when managing dependencies for PHP as a whole on your system. * Use **PEAR** when managing dependencies for PHP as a whole on your system.
In general, Composer packages will be available only in the projects that you explicitly specify whereas a PEAR package would be available to all of your PHP projects. While PEAR might sound like the easier approach at first glance, there are advantages to using a project-by-project approach to your dependencies. In general, Composer packages will be available only in the projects that you explicitly specify whereas a PEAR package
would be available to all of your PHP projects. While PEAR might sound like the easier approach at first glance, there
are advantages to using a project-by-project approach to your dependencies.

View File

@@ -5,24 +5,36 @@ anchor: composer_and_packagist
## Composer and Packagist {#composer_and_packagist_title} ## 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 ### 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 #### 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) ### 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 - a sufficient version of PHP is being used
- `.phar` files can be executed correctly - `.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 problematic extensions are not loaded
- certain `php.ini` settings are set - 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 {% highlight console %}
chmod +x $HOME/local/bin/composer 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:
composer install {% highlight console %}
composer install
{% endhighlight %}
This section will assume you have installed composer globally. This section will assume you have installed composer globally.
### How to Define and Install Dependencies ### 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 %} {% highlight php %}
<?php <?php
@@ -64,9 +93,15 @@ Now you can use your project dependencies, and they'll be autoloaded on demand.
### Updating your dependencies ### 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 ### Update Notifications
@@ -75,14 +110,15 @@ your GitHub and BitBucket accounts for `composer.json` files and send emails wit
### Checking your dependencies for security issues ### 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] * [Learn about Composer][5]
[1]: http://packagist.org/ [1]: http://packagist.org/
[2]: http://twig.sensiolabs.org [2]: http://twig.sensiolabs.org
[3]: https://www.versioneye.com/ [3]: https://www.versioneye.com/
[4]: https://security.sensiolabs.org/ [4]: https://security.sensiolabs.org/
[5]: http://getcomposer.org/doc/00-intro.md [5]: http://getcomposer.org/doc/00-intro.md
[6]: https://getcomposer.org/Composer-Setup.exe [6]: https://getcomposer.org/Composer-Setup.exe

View File

@@ -8,12 +8,12 @@ anchor: pear
Another veteran package manager that many PHP developers enjoy is [PEAR][1]. It behaves much the same way as Composer, 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. 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 PEAR requires each package to have a specific structure, which means that the author of the package must prepare it for
for usage with PEAR. Using a project which was not prepared to work with PEAR is not possible. 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 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 server. This can be good if many projects rely on the same package with the same version but might lead to problems if
if version conflicts between two projects arise. version conflicts between two projects arise.
### How to install PEAR ### How to install PEAR
@@ -27,7 +27,9 @@ 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: If the package is listed on the [PEAR packages list][3], you can install it by specifying the official name:
pear install foo {% 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 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. installing. See the [Using channel docs][4] for more information on this topic.
@@ -36,8 +38,8 @@ installing. See the [Using channel docs][4] for more information on this topic.
### Handling PEAR dependencies with Composer ### 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 If you are already using [Composer][5] and you would like to install some PEAR code too, you can use Composer to
Composer to handle your PEAR dependencies. This example will install code from `pear2.php.net`: handle your PEAR dependencies. This example will install code from `pear2.php.net`:
{% highlight json %} {% highlight json %}
{ {
@@ -54,28 +56,29 @@ Composer to handle your PEAR dependencies. This example will install code from `
} }
{% endhighlight %} {% endhighlight %}
The first section `"repositories"` will be used to let Composer know it should "initialise" The first section `"repositories"` will be used to let Composer know it should "initialise" (or "discover" in PEAR
(or "discover" in PEAR terminology) the pear repo. Then the require section will prefix the package terminology) the pear repo. Then the require section will prefix the package name like this:
name like this:
> pear-channel/Package > 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 The "pear" prefix is hardcoded to avoid any conflicts, as a pear channel could be the same as another packages vendor
to reference which channel the package is in. 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 When this code is installed it will be available in your vendor directory and automatically available through the
available through the Composer autoloader: Composer autoloader:
> vendor/pear-pear2.php.net/PEAR2_HTTP_Request/pear2/HTTP/Request.php > vendor/pear-pear2.php.net/PEAR2_HTTP_Request/pear2/HTTP/Request.php
To use this PEAR package simply reference it like so: To use this PEAR package simply reference it like so:
{% highlight php %} {% highlight php %}
<?php
$request = new pear2\HTTP\Request(); $request = new pear2\HTTP\Request();
{% endhighlight %} {% endhighlight %}
* [Learn more about using PEAR with Composer][6] * [Learn more about using PEAR with Composer][6]
[1]: http://pear.php.net/ [1]: http://pear.php.net/
[2]: http://pear.php.net/manual/en/installation.getting.php [2]: http://pear.php.net/manual/en/installation.getting.php
[3]: http://pear.php.net/packages.php [3]: http://pear.php.net/packages.php

View File

@@ -5,30 +5,32 @@ anchor: date_and_time
## Date and Time {#date_and_time_title} ## 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 PHP has a class named DateTime to help you when reading, writing, comparing or calculating with date and time. There
many date and time related functions in PHP besides DateTime, but it provides nice object-oriented interface to most are many date and time related functions in PHP besides DateTime, but it provides nice object-oriented interface to
common uses. It can handle time zones, but that is outside this short introduction. 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 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. output.
{% highlight php %} {% highlight php %}
<?php <?php
$raw = '22. 11. 1968'; $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"; echo 'Start date: ' . $start->format('Y-m-d') . "\n";
{% endhighlight %} {% endhighlight %}
Calculating with DateTime is possible with the DateInterval class. DateTime has methods like `add()` and `sub()` that 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 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 saving and timezone alterations will break that assumption. Use date intervals instead. To calculate date difference
the `diff()` method. It will return new DateInterval, which is super easy to display. use the `diff()` method. It will return new DateInterval, which is super easy to display.
{% highlight php %} {% highlight php %}
<?php <?php
// create a copy of $start and add one month and 6 days // create a copy of $start and add one month and 6 days
$end = clone $start; $end = clone $start;
$end->add(new \DateInterval('P1M6D')); $end->add(new DateInterval('P1M6D'));
$diff = $end->diff($start); $diff = $end->diff($start);
echo 'Difference: ' . $diff->format('%m month, %d days (total: %a days)') . "\n"; 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 %} {% endhighlight %}
On DateTime objects you can use standard comparison: On DateTime objects you can use standard comparison:
{% highlight php %} {% highlight php %}
<?php <?php
if ($start < $end) { 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 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. DateTime objects, start and end, and the interval for which it will return all events in between.
{% highlight php %} {% highlight php %}
<?php <?php
// output all thursdays between $start and $end // output all thursdays between $start and $end
$periodInterval = \DateInterval::createFromDateString('first thursday'); $periodInterval = DateInterval::createFromDateString('first thursday');
$periodIterator = new \DatePeriod($start, $periodInterval, $end, \DatePeriod::EXCLUDE_START_DATE); $periodIterator = new DatePeriod($start, $periodInterval, $end, DatePeriod::EXCLUDE_START_DATE);
foreach ($periodIterator as $date) { foreach ($periodIterator as $date) {
// output each date in the period // output each date in the period
echo $date->format('Y-m-d') . ' '; echo $date->format('Y-m-d') . ' ';
@@ -59,5 +63,5 @@ foreach ($periodIterator as $date) {
* [Read about DateTime][datetime] * [Read about DateTime][datetime]
* [Read about date formatting][dateformat] (accepted date format string options) * [Read about date formatting][dateformat] (accepted date format string options)
[datetime]: http://www.php.net/manual/book.datetime.php [datetime]: http://php.net/book.datetime
[dateformat]: http://www.php.net/manual/function.date.php [dateformat]: http://php.net/function.date

View File

@@ -32,20 +32,20 @@ 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. of luck.
You should use the `mb_internal_encoding()` function at the top of every PHP script you write (or at the You should use the `mb_internal_encoding()` function at the top of every PHP script you write (or at the top of your
top of your global include script), and the `mb_http_output()` function right after it if your script is outputting to global include script), and the `mb_http_output()` function right after it if your script is outputting to a browser.
a browser. Explicitly defining the encoding of your strings in every script will save you a lot of headaches down the Explicitly defining the encoding of your strings in every script will save you a lot of headaches down the road.
road.
Additionally, many PHP functions that operate on strings have an optional parameter letting you specify the character 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 encoding. You should always explicitly indicate UTF-8 when given the option. For example, `htmlentities()` has an
option for character encoding, and you should always specify UTF-8 if dealing with such strings. Note that as of PHP 5.4.0, UTF-8 is the default encoding for `htmlentities()` and `htmlspecialchars()`. option for character encoding, and you should always specify UTF-8 if dealing with such strings. Note that as of PHP 5.
4.0, UTF-8 is the default encoding for `htmlentities()` and `htmlspecialchars()`.
Finally, If you are building an distributed application and cannot be certain that the `mbstring` extension will be 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 enabled, then consider using the [patchwork/utf8] Composer package. This will use `mbstring` if it is available, and
will use `mbstring` if it is available, and fall back to non UTF-8 functions if not. 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 [patchwork/utf8]: https://packagist.org/packages/patchwork/utf8
### UTF-8 at the Database level ### UTF-8 at the Database level
@@ -64,7 +64,10 @@ Further Reading for why.
Use the `mb_http_output()` function to ensure that your PHP script outputs UTF-8 strings to your browser. 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 %} {% highlight php %}
<?php <?php
@@ -84,13 +87,13 @@ $string = mb_substr($string, 0, 15);
// Connect to a database to store the transformed string // Connect to a database to store the transformed string
// See the PDO example in this document for more information // See the PDO example in this document for more information
// Note the `set names utf8mb4` commmand! // Note the `set names utf8mb4` commmand!
$link = new \PDO( $link = new PDO(
'mysql:host=your-hostname;dbname=your-db;charset=utf8mb4', 'mysql:host=your-hostname;dbname=your-db;charset=utf8mb4',
'your-username', 'your-username',
'your-password', 'your-password',
array( array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false PDO::ATTR_PERSISTENT => false
) )
); );
@@ -128,20 +131,21 @@ header('Content-Type: text/html; charset=UTF-8');
### Further reading ### Further reading
* [PHP Manual: String Operations](http://php.net/manual/en/language.operators.string.php) * [PHP Manual: String Operations](http://php.net/language.operators.string)
* [PHP Manual: String Functions](http://php.net/manual/en/ref.strings.php) * [PHP Manual: String Functions](http://php.net/ref.strings)
* [`strpos()`](http://php.net/manual/en/function.strpos.php) * [`strpos()`](http://php.net/function.strpos)
* [`strlen()`](http://php.net/manual/en/function.strlen.php) * [`strlen()`](http://php.net/function.strlen)
* [`substr()`](http://php.net/manual/en/function.substr.php) * [`substr()`](http://php.net/function.substr)
* [PHP Manual: Multibyte String Functions](http://php.net/manual/en/ref.mbstring.php) * [PHP Manual: Multibyte String Functions](http://php.net/ref.mbstring)
* [`mb_strpos()`](http://php.net/manual/en/function.mb-strpos.php) * [`mb_strpos()`](http://php.net/function.mb-strpos)
* [`mb_strlen()`](http://php.net/manual/en/function.mb-strlen.php) * [`mb_strlen()`](http://php.net/function.mb-strlen)
* [`mb_substr()`](http://php.net/manual/en/function.mb-substr.php) * [`mb_substr()`](http://php.net/function.mb-substr)
* [`mb_internal_encoding()`](http://php.net/manual/en/function.mb-internal-encoding.php) * [`mb_internal_encoding()`](http://php.net/function.mb-internal-encoding)
* [`mb_http_output()`](http://php.net/manual/en/function.mb-http-output.php) * [`mb_http_output()`](http://php.net/function.mb-http-output)
* [`htmlentities()`](http://php.net/manual/en/function.htmlentities.php) * [`htmlentities()`](http://php.net/function.htmlentities)
* [`htmlspecialchars()`](http://www.php.net/manual/en/function.htmlspecialchars.php) * [`htmlspecialchars()`](http://php.net/function.htmlspecialchars)
* [PHP UTF-8 Cheatsheet](http://blog.loftdigital.com/blog/php-utf-8-cheatsheet) * [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: 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) * [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) * [How to support full Unicode in MySQL databases](http://mathiasbynens.be/notes/mysql-utf8mb4)

View File

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

View File

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

View File

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

View File

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

@@ -5,8 +5,8 @@ anchor: further_reading
## Further Reading {#further_reading_title} ## Further Reading {#further_reading_title}
- [Learning about Dependency Injection and PHP](http://ralphschindler.com/2011/05/18/learning-about-dependency-injection-and-php) * [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) * [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: 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: 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/) * [Dependency Injection as a tool for testing](http://philipobenito.github.io/dependency-injection-as-a-tool-for-testing/)

View File

@@ -6,94 +6,14 @@ anchor: databases
# Databases {#databases_title} # Databases {#databases_title}
Many times your PHP code will use a database to persist information. You have a few options to connect and interact 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 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 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
drivers. You'll need to learn a brand new API for each database &mdash; and that can get silly. 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 [mysqli]: http://php.net/mysqli
[pgsql]: http://php.net/pgsql [pgsql]: http://php.net/pgsql
[mssql]: http://php.net/mssql [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

@@ -19,9 +19,11 @@ foreach ($db->query('SELECT * FROM table') as $row) {
</ul> </ul>
{% endhighlight %} {% 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: 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. 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** **foo.php**
{% highlight php %} {% highlight php %}
<?php <?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password'); $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
// Make your model available // Make your model available
@@ -85,11 +88,13 @@ class Foo()
<?php endforeach ?> <?php endforeach ?>
{% endhighlight %} {% endhighlight %}
This is essentially the same as what most modern frameworks are doing, all be it a little more manual. You might This is essentially the same as what most modern frameworks are doing, all be it a little more manual. You might not
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. 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 [MVC]: http://code.tutsplus.com/tutorials/mvc-for-noobs--net-10488
[PHPBridge]: http://phpbridge.org/ [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

@@ -8,5 +8,4 @@ anchor: templating
Templates provide a convenient way of separating your controller and domain logic from your presentation logic. 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 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 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) [modelviewcontroller](/pages/Design-Patterns.html#model-view-controller) (MVC) software architecture pattern.
software architecture pattern.

View File

@@ -12,13 +12,12 @@ code editors already have PHP syntax highlighting and auto-completion built-in.
very fast as no compiling stage is required. 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 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 frameworks, libraries like [Plates][plates] or [Aura.View][aura] make working with plain PHP templates easier by
working with plain PHP templates easier by offering modern template functionality such as inheritance, layouts and offering modern template functionality such as inheritance, layouts and extensions.
extensions.
### Simple example of a plain PHP template ### Simple example of a plain PHP template
Using the [Plates](http://platesphp.com/) library. Using the [Plates][plates] library.
{% highlight php %} {% highlight php %}
<?php // user_profile.php ?> <?php // user_profile.php ?>
@@ -33,7 +32,7 @@ Using the [Plates](http://platesphp.com/) library.
### Example of plain PHP templates using inheritance ### Example of plain PHP templates using inheritance
Using the [Plates](http://platesphp.com/) library. Using the [Plates][plates] library.
{% highlight php %} {% highlight php %}
<?php // template.php ?> <?php // template.php ?>
@@ -60,3 +59,7 @@ Using the [Plates](http://platesphp.com/) library.
<h1>User Profile</h1> <h1>User Profile</h1>
<p>Hello, <?=$this->escape($name)?></p> <p>Hello, <?=$this->escape($name)?></p>
{% endhighlight %} {% endhighlight %}
[plates]: http://platesphp.com/
[aura]: https://github.com/auraphp/Aura.View

View File

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

@@ -7,22 +7,22 @@ anchor: templating_further_reading
### Articles & Tutorials ### Articles & Tutorials
- [Templating Engines in PHP](http://fabien.potencier.org/article/34/templating-engines-in-php) * [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) * [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/) * [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) * [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) * [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) * [Working With Templates in Symfony 2](http://code.tutsplus.com/tutorials/working-with-templates-in-symfony-2--cms-21172)
### Libraries ### Libraries
- [Aura.View](https://github.com/auraphp/Aura.View) *(native)* * [Aura.View](https://github.com/auraphp/Aura.View) *(native)*
- [Blade](http://laravel.com/docs/templates) *(compiled, framework specific)* * [Blade](http://laravel.com/docs/templates) *(compiled, framework specific)*
- [Dwoo](http://dwoo.org/) *(compiled)* * [Dwoo](http://dwoo.org/) *(compiled)*
- [Latte](https://github.com/nette/latte) *(compiled)* * [Latte](https://github.com/nette/latte) *(compiled)*
- [Mustache](https://github.com/bobthecow/mustache.php) *(compiled)* * [Mustache](https://github.com/bobthecow/mustache.php) *(compiled)*
- [PHPTAL](http://phptal.org/) *(compiled)* * [PHPTAL](http://phptal.org/) *(compiled)*
- [Plates](http://platesphp.com/) *(native)* * [Plates](http://platesphp.com/) *(native)*
- [Smarty](http://www.smarty.net/) *(compiled)* * [Smarty](http://www.smarty.net/) *(compiled)*
- [Twig](http://twig.sensiolabs.org/) *(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)* * [Zend\View](http://framework.zend.com/manual/2.3/en/modules/zend.view.quick-start.html) *(native, framework specific)*

View File

@@ -12,16 +12,16 @@ processing regardless of what happens, unless a fatal error occurs.
For example: For example:
{% highlight php %} {% highlight console %}
$ php -a $ php -a
php > echo $foo; php > echo $foo;
Notice: Undefined variable: foo in php shell code on line 1 Notice: Undefined variable: foo in php shell code on line 1
{% endhighlight %} {% endhighlight %}
This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from "exception-heavy" This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from
languages, because referencing a missing variable in Python for example will throw an exception: "exception-heavy" languages, because referencing a missing variable in Python for example will throw an exception:
{% highlight python %} {% highlight console %}
$ python $ python
>>> print foo >>> print foo
Traceback (most recent call last): Traceback (most recent call last):
@@ -37,7 +37,9 @@ point it will throw an error and report it.
PHP has several levels of error severity. The three most common types of messages are errors, notices and warnings. 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 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. 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 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. changes to your code to help ensure best interoperability and forward compatibility with upcoming versions of PHP.
@@ -46,10 +48,11 @@ changes to your code to help ensure best interoperability and forward compatibil
Error Reporting can be changed by using PHP settings and/or PHP function calls. Using the built in PHP function 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 `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 predefined error level constants, meaning if you only want to see Warnings and Errors - but not Notices - then you can
you can configure that: configure that:
{% highlight php %} {% highlight php %}
<?php
error_reporting(E_ERROR | E_WARNING); error_reporting(E_ERROR | E_WARNING);
{% endhighlight %} {% endhighlight %}
@@ -58,75 +61,99 @@ You can also control whether or not errors are displayed to the screen (good for
### Inline Error Suppression ### Inline Error Suppression
You can also tell PHP to suppress specific errors with the Error Control Operator `@`. You put You can also tell PHP to suppress specific errors with the Error Control Operator `@`. You put this operator at the
this operator at the beginning of an expression, and any error that's a direct result of the expression is silenced. beginning of an expression, and any error that's a direct result of the expression is silenced.
{% highlight php %} {% highlight php %}
<?php
echo @$foo['bar']; echo @$foo['bar'];
{% endhighlight %} {% endhighlight %}
This will output `$foo['bar']` if it exists, but will simply return a null and print nothing if the variable `$foo` or 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. `'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 %} {% highlight php %}
<?php
echo isset($foo['bar']) ? $foo['bar'] : ''; echo isset($foo['bar']) ? $foo['bar'] : '';
{% endhighlight %} {% endhighlight %}
One instance where error suppression might make sense is where `fopen()` fails to find a file to load. You could check 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()` for the existence of the file before you try to load it, but if the file is deleted after the check and before the
(which might sound impossible, but it can happen) then `fopen()` will return false _and_ throw an error. This is `fopen()` (which might sound impossible, but it can happen) then `fopen()` will return false _and_ throw an error. This
potentially something PHP should resolve, but is one case where error suppression might seem like the only valid is potentially something PHP should resolve, but is one case where error suppression might seem like the only valid
solution. 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 You can also set this value at runtime with the `ini_set` function
{% highlight php %} {% highlight php %}
<?php
ini_set('xdebug.scream', '1') ini_set('xdebug.scream', '1')
{% endhighlight %} {% 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) * [Error Control Operators]
* [SitePoint](http://www.sitepoint.com/) * [SitePoint]
* [xDebug] * [xDebug]
* [Scream] * [Scream]
[xDebug]: http://xdebug.org/docs/basic
[Scream]: http://www.php.net/manual/en/book.scream.php
### ErrorException ### ErrorException
PHP is perfectly capable of being an "exception-heavy" programming language, and only requires a few lines of code to 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. 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 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 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. 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 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. 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 More information on this and details on how to use `ErrorException` with error handling can be found at
[ErrorException Class][errorexception]. [ErrorException Class][errorexception].
* [Error Control Operators](http://php.net/manual/en/language.operators.errorcontrol.php) * [Error Control Operators]
* [Predefined Constants for Error Handling](http://www.php.net/manual/en/errorfunc.constants.php) * [Predefined Constants for Error Handling]
* [error_reporting](http://www.php.net/manual/en/function.error-reporting.php) * [`error_reporting()`][error_reporting]
* [Reporting][errorreport] * [Reporting][errorreport]
[errorexception]: http://php.net/manual/en/class.errorexception.php
[errorreport]: /#error_reporting [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/ [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

@@ -10,15 +10,16 @@ Languages like Ruby are extremely Exception heavy, so whenever something goes wr
a DB query goes wrong, or even if an image asset could not be found, Ruby (or the gems being used) will throw an 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. 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. 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 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 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 looking for a mistake and check the docs to see what the error method is for this class, instead of having it made
obvious. extremely obvious.
Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you 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 stop another developer from being able to dynamically handle that error. Exceptions should be thrown to make a
aware of an error; they then can choose how to handle this. E.g.: developer aware of an error; they then can choose how to handle this. E.g.:
{% highlight php %} {% highlight php %}
<?php <?php
@@ -47,28 +48,30 @@ finally
### SPL Exceptions ### SPL Exceptions
The generic `Exception` class provides very little debugging context for the developer; however, to remedy this, The generic `Exception` class provides very little debugging context for the developer; however, to remedy this, it is
it is possible to create a specialized `Exception` type by sub-classing the generic `Exception` class: possible to create a specialized `Exception` type by sub-classing the generic `Exception` class:
{% highlight php %} {% highlight php %}
<?php <?php
class ValidationException extends Exception {} class ValidationException extends Exception {}
{% endhighlight %} {% endhighlight %}
This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to the
the creation of a <em>lot</em> of custom Exceptions, some of which could have been avoided using the SPL Exceptions 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]. 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 If for example you use the `__call()` Magic Method and an invalid method is requested then instead of throwing a
Exception which is vague, or creating a custom Exception just for that, you could just `throw new BadMethodCallException;`. 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 Exceptions][exceptions]
* [Read about SPL Exceptions][splexe] * [Read about SPL Exceptions][splexe]
* [Nesting Exceptions In PHP][nesting-exceptions-in-php] * [Nesting Exceptions In PHP][nesting-exceptions-in-php]
* [Exception Best Practices in PHP 5.3][exception-best-practices53] * [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 [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/ [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

@@ -5,10 +5,13 @@ anchor: web_application_security
## Web Application Security {#web_application_security_title} ## Web Application Security {#web_application_security_title}
There are bad people ready and willing to exploit your web application. It is important that you There are bad people ready and willing to exploit your web application. It is important that you take necessary
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. 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] * [Read the OWASP Security Guide][2]
[1]: https://www.owasp.org/ [1]: https://www.owasp.org/
[2]: https://www.owasp.org/index.php/Guide_Table_of_Contents [2]: https://www.owasp.org/index.php/Guide_Table_of_Contents

View File

@@ -5,19 +5,27 @@ anchor: password_hashing
## Password Hashing {#password_hashing_title} ## 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`** **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 %} {% highlight php %}
<?php <?php
require 'password.php'; require 'password.php';
$passwordHash = password_hash('secret-password', PASSWORD_DEFAULT); $passwordHash = password_hash('secret-password', PASSWORD_DEFAULT);
@@ -30,13 +38,13 @@ if (password_verify('bad-password', $passwordHash)) {
{% endhighlight %} {% endhighlight %}
* [Learn about `password_hash()`] [1]
* [Learn about `password_hash`] [1]
* [`password_compat` for PHP >= 5.3.7 && < 5.5] [2] * [`password_compat` for PHP >= 5.3.7 && < 5.5] [2]
* [Learn about hashing in regards to cryptography] [3] * [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 [2]: https://github.com/ircmaxell/password_compat
[3]: http://en.wikipedia.org/wiki/Cryptographic_hash_function [3]: http://en.wikipedia.org/wiki/Cryptographic_hash_function
[4]: https://wiki.php.net/rfc/password_hash [4]: https://wiki.php.net/rfc/password_hash

View File

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

View File

@@ -5,12 +5,12 @@ anchor: configuration_files
## Configuration Files {#configuration_files_title} ## Configuration Files {#configuration_files_title}
When creating configuration files for your applications, best practices recommend that one of the following methods When creating configuration files for your applications, best practices recommend that one of the following methods be
be followed: 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. via the file system.
- If you must store your configuration files in the document root, name the files with a `.php` extension. This - If you must store your configuration files in the document root, name the files with a `.php` extension. This ensures
ensures that, even if the script is accessed directly, it will not be output as plain text. 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 - Information in configuration files should be protected accordingly, either through encryption or group/user file
system permissions system permissions

View File

@@ -5,14 +5,14 @@ anchor: register_globals
## Register Globals {#register_globals_title} ## Register Globals {#register_globals_title}
**NOTE:** As of PHP 5.4.0 the `register_globals` setting has been removed and can no **NOTE:** As of PHP 5.4.0 the `register_globals` setting has been removed and can no longer be used. This is only
longer be used. This is only included as a warning for anyone in the process of upgrading a legacy application. 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 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 `$_POST`, `$_GET` and `$_REQUEST`) available in the global scope of your application. This can easily lead to security
security issues as your application cannot effectively tell where the data is coming from. 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__. 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

@@ -14,16 +14,19 @@ production (live).
To show every possible error during <strong>development</strong>, configure the following settings in your `php.ini`: To show every possible error during <strong>development</strong>, configure the following settings in your `php.ini`:
display_errors = On {% highlight ini %}
display_startup_errors = On display_errors = On
error_reporting = -1 display_startup_errors = On
log_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 The `E_STRICT` error level constant was introduced in 5.3.0 and is not part of `E_ALL`, however it became part of
part of `E_ALL`, however it became part of `E_ALL` in 5.4.0. What does this mean? `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
In terms of reporting every possible error in version 5.3 it means you must
use either `-1` or `E_ALL | E_STRICT`. use either `-1` or `E_ALL | E_STRICT`.
**Reporting every possible error by PHP version** **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: To hide errors on your <strong>production</strong> environment, configure your `php.ini` as:
display_errors = Off {% highlight ini %}
display_startup_errors = Off display_errors = Off
error_reporting = E_ALL display_startup_errors = Off
log_errors = On 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: 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) * [error_reporting](http://php.net/errorfunc.configuration#ini.error-reporting)
* [display_errors](http://php.net/manual/errorfunc.configuration.php#ini.display-errors) * [display_errors](http://php.net/errorfunc.configuration#ini.display-errors)
* [display_startup_errors](http://php.net/manual/errorfunc.configuration.php#ini.display-startup-errors) * [display_startup_errors](http://php.net/errorfunc.configuration#ini.display-startup-errors)
* [log_errors](http://php.net/manual/errorfunc.configuration.php#ini.log-errors) * [log_errors](http://php.net/errorfunc.configuration#ini.log-errors)

View File

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

View File

@@ -7,29 +7,33 @@ anchor: test_driven_development
From [Wikipedia](http://en.wikipedia.org/wiki/Test-driven_development): 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
Unit Testing is a programming approach to ensure functions, classes and methods are working as Unit Testing is a programming approach to ensure functions, classes and methods are working as expected, from the point
expected, from the point you build them all the way through the development cycle. By checking you build them all the way through the development cycle. By checking values going in and out of various functions and
values going in and out of various functions and methods, you can make sure the internal logic is methods, you can make sure the internal logic is working correctly. By using Dependency Injection and building "mock"
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. 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 When you create a class or function you should create a unit test for each behavior it must have. At a very basic level
make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments. you should make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments. This
This will help ensure that when you make changes to this class or function later on in the development will help ensure that when you make changes to this class or function later on in the development cycle that the old
cycle that the old functionality continues to work as expected. The only alternative to this would be functionality continues to work as expected. The only alternative to this would be `var_dump()` in a test.php, which is
var_dump() in a test.php, which is no way to build an application - large or small. 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 The other use for unit tests is contributing to open source. If you can write a test that shows broken functionality
functionality (i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If (i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If you run a project
you run a project which accepts pull requests then you should suggest this as a requirement. 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 [PHPUnit](http://phpunit.de) is the de-facto testing framework for writing unit tests for PHP applications, but there
applications, but there are several alternatives are several alternatives
* [atoum](https://github.com/atoum/atoum) * [atoum](https://github.com/atoum/atoum)
* [Enhance PHP](https://github.com/Enhance-PHP/Enhance-PHP) * [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): 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 Many of the same tools that can be used for unit testing can be used for integration testing as many of the same
of the same principles are used. principles are used.
### Functional Testing ### Functional Testing
Sometimes also known as acceptance testing, functional testing consists of using tools to create automated Sometimes also known as acceptance testing, functional testing consists of using tools to create automated tests that
tests that actually use your application instead of just verifying that individual units of code are behaving actually use your application instead of just verifying that individual units of code are behaving correctly and that
correctly and that individual units can speak to each other correctly. These tools typically work using real individual units can speak to each other correctly. These tools typically work using real data and simulating actual
data and simulating actual users of the application. users of the application.
#### Functional Testing Tools #### Functional Testing Tools

View File

@@ -5,19 +5,27 @@ anchor: behavior_driven_development
## Behavior Driven Development {#behavior_driven_development_title} ## 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 With StoryBDD, you write human-readable stories that describe the behavior of your application. These stories can then
can then be run as actual tests against your application. The framework used in PHP applications for StoryBDD be run as actual tests against your application. The framework used in PHP applications for StoryBDD is [Behat], which
is Behat, which is inspired by Ruby's [Cucumber](http://cukes.info/) project and implements the Gherkin DSL is inspired by Ruby's [Cucumber] project and implements the Gherkin DSL for describing feature behavior.
for describing feature behavior.
With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing a function
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 or method, you are describing how that function or method should behave. PHP offers the [PHPSpec] framework for this
by the [RSpec project](http://rspec.info/) for Ruby. purpose. This framework is inspired by the [RSpec project][Rspec] for Ruby.
### BDD Links ### BDD Links
* [Behat](http://behat.org/), the StoryBDD framework for PHP, inspired by Ruby's [Cucumber](http://cukes.info/) project; * [Behat], the StoryBDD framework for PHP, inspired by Ruby's [Cucumber] project;
* [PHPSpec](http://www.phpspec.net/), the SpecBDD framework for PHP, inspired by Ruby's [RSpec](http://rspec.info/) project; * [PHPSpec], the SpecBDD framework for PHP, inspired by Ruby's [RSpec] project;
* [Codeception](http://codeception.com) is a full-stack testing framework that uses BDD principles. * [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

@@ -5,10 +5,20 @@ anchor: complementary_testing_tools
## Complementary Testing Tools {#complementary_testing_tools_title} ## 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 ### 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) * [Selenium] is a browser automation tool which can be [integrated with PHPUnit]
* [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/) * [Mockery] is a Mock Object Framework which can be integrated with [PHPUnit] or [PHPSpec]
* [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/). * [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

@@ -10,4 +10,4 @@ PaaS provides the system and network architecture necessary to run PHP applicati
configuration for launching PHP applications or PHP frameworks. 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 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). find a list of [PHP PaaS "Platform as a Service" providers](#php_paas_providers) in our [resources section](#resources).

View File

@@ -5,25 +5,49 @@ anchor: virtual_or_dedicated_servers
## Virtual or Dedicated Servers {#virtual_or_dedicated_servers_title} ## 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 ### 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 nginx][nginx]
* [Read more on PHP-FPM](http://php.net/manual/en/install.fpm.php) * [Read more on PHP-FPM][phpfpm]
* [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 setting up nginx and PHP-FPM securely][secure-nginx-phpfpm]
### Apache and PHP ### 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 Apache][apache]
* [Read more on Multi-Processing Modules](http://httpd.apache.org/docs/2.4/mod/mpm_common.html) * [Read more on Multi-Processing Modules][apache-MPM]
* [Read more on mod_fastcgi](http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html) * [Read more on mod_fastcgi][mod_fastcgi]
* [Read more on mod_fcgid](http://httpd.apache.org/mod_fcgid/) * [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

@@ -5,4 +5,8 @@ anchor: shared_servers
## Shared Servers {#shared_servers_title} ## 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

@@ -7,9 +7,8 @@ anchor: building_and_deploying_your_application
If you find yourself doing manual database schema changes or running your tests manually before updating your files 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 (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 potentially fatal mistakes increase. Whether you're dealing with a simple update, a comprehensive build process or even
even a continuous integration strategy, [build automation](http://en.wikipedia.org/wiki/Build_automation) is your a continuous integration strategy, [build automation][buildautomation] is your friend.
friend.
Among the tasks you might want to automate are: Among the tasks you might want to automate are:
@@ -23,36 +22,37 @@ Among the tasks you might want to automate are:
### Build Automation Tools ### Build Automation Tools
Build tools can be described as a collection of scripts that handle common tasks of software deployment. The build Build tools can be described as a collection of scripts that handle common tasks of software deployment. The build tool
tool is not a part of your software, it acts on your software from 'outside'. 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: 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] is the easiest way to get started with automated deployment in the PHP world. With Phing you can control your
Phing you can control your packaging, deployment or testing process from within a simple XML build file. Phing (which packaging, deployment or testing process from within a simple XML build file. Phing (which is based on [Apache Ant])
is based on [Apache Ant](http://ant.apache.org/)) provides a rich set of tasks usually needed to install or update a provides a rich set of tasks usually needed to install or update a web app and can be extended with additional custom
web app and can be extended with additional custom tasks, written in PHP. tasks, written in PHP.
[Capistrano](https://github.com/capistrano/capistrano/wiki) is a system for *intermediate-to-advanced programmers* to [Capistrano] is a system for *intermediate-to-advanced programmers* to execute commands in a structured, repeatable way
execute commands in a structured, repeatable way on one or more remote machines. It is pre-configured for deploying on one or more remote machines. It is pre-configured for deploying Ruby on Rails applications, however people are **
Ruby on Rails applications, however people are **successfully deploying PHP systems** with it. Successful use of successfully deploying PHP systems** with it. Successful use of Capistrano depends on a working knowledge of Ruby and
Capistrano depends on a working knowledge of Ruby and Rake. Rake.
Dave Gardner's blog post [PHP Deployment with Capistrano](http://www.davegardner.me.uk/blog/2012/02/13/php-deployment-with-capistrano/) Dave Gardner's blog post [PHP Deployment with Capistrano][phpdeploy_capistrano] is a good starting point for PHP
is a good starting point for PHP developers interested in Capistrano. developers interested in Capistrano.
[Chef](http://www.opscode.com/chef/) is more than a deployment framework, it is a very powerful Ruby based system [Chef] is more than a deployment framework, it is a very powerful Ruby based system integration framework that doesn't
integration framework that doesn't just deploy your app but can build your whole server environment or virtual boxes. 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/) * [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](https://github.com/opscode-cookbooks/php) * [Chef Cookbook which installs and configures PHP 5.3 and the PEAR package management system][Chef_cookbook]
* [Chef video tutorial series by Opscode, the makers of chef](https://www.youtube.com/playlist?list=PLrmstJpucjzWKt1eWLv88ZFY4R1jW8amR) * [Chef video tutorial series][Chef_tutorial] by Opscode, the makers of chef
Further reading:
* [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
@@ -63,13 +63,29 @@ Further reading:
*-- Martin Fowler* *-- Martin Fowler*
There are different ways to implement continuous integration for PHP. Recently [Travis CI](https://travis-ci.org/) has There are different ways to implement continuous integration for PHP. Recently [Travis CI] has done a great job of
done a great job of making continuous integration a reality even for small projects. Travis CI is a hosted continuous making continuous integration a reality even for small projects. Travis CI is a hosted continuous integration service
integration service for the open source community. It is integrated with GitHub and offers first class support for many for the open source community. It is integrated with GitHub and offers first class support for many languages including
languages including PHP. PHP.
Further reading: #### Further reading:
* [Continuous Integration with Jenkins](http://jenkins-ci.org/) * [Continuous Integration with Jenkins][Jenkins]
* [Continuous Integration with PHPCI](http://www.phptesting.org/) * [Continuous Integration with PHPCI][PHPCI]
* [Continuous Integration with Teamcity](http://www.jetbrains.com/teamcity/) * [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 # Virtualization
Running your application on different environments in development and production can lead to strange bugs Running your application on different environments in development and production can lead to strange bugs popping up
popping up when you go live. It's also tricky to keep different development environments up to date with the same when you go live. It's also tricky to keep different development environments up to date with the same version for all
version for all libraries used when working with a team of developers. 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 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. should consider using a virtual machine. This sounds tricky, but besides the widely known virtualization environments
This sounds tricky, but besides the widely known virtualization environments like VMware or VirtualBox, there are like VMware or VirtualBox, there are additional tools that may help you setting up a virtual environment in a few easy
additional tools that may help you setting up a virtual environment in a few easy steps. steps.

View File

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

View File

@@ -5,38 +5,41 @@ anchor: docker
## Docker {#docker_title} ## 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. 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 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. these services on your local machine, e.g. MySQL or PostgreSQL and a lot more. Have a look at the [Docker Hub Registry]
Have a look at the [Docker Hub Registry][docker-hub] to search a list of available pre-built containers, [docker-hub] to search a list of available pre-built containers, which you can then run and use in very few steps.
which you can then run and use in very few steps.
### Example: Runnning your PHP Applications in Docker ### 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 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`: directory `/path/to/your/php/files` at `http://localhost:8080`:
{% highlight bash %} {% highlight console %}
docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache
{% endhighlight %} {% 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 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. `docker stop my-php-webserver` and `docker start my-php-webserver` without providing the above mentioned parameters
again.
### Learn more about 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] 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 Installation][docker-install]
* [Docker Images at the Docker Hub Registry][docker-hub] * [Docker Images at the Docker Hub Registry][docker-hub]
* [Docker User Guide][docker-doc] * [Docker User Guide][docker-doc]
[docker]: http://docker.com/
[Docker]: http://docker.com/
[docker-hub]: https://registry.hub.docker.com/ [docker-hub]: https://registry.hub.docker.com/
[docker-install]: https://docs.docker.com/installation/ [docker-install]: https://docs.docker.com/installation/
[docker-doc]: https://docs.docker.com/userguide/ [docker-doc]: https://docs.docker.com/userguide/

View File

@@ -6,20 +6,29 @@ anchor: opcode_cache
## Opcode Cache {#opcode_cache_title} ## 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. 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. This is where opcode caches come in. They prevent redundant compilation by storing opcodes in memory and reusing it on
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. 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: Read more about opcode caches:
* [OPcache][opcache-book] (built-in since PHP 5.5) * [OPcache][opcache-book] (built-in since PHP 5.5)
* [APC](http://php.net/manual/en/book.apc.php) (PHP 5.4 and earlier) * [APC] (PHP 5.4 and earlier)
* [XCache](http://xcache.lighttpd.net/) * [XCache]
* [Zend Optimizer+](http://www.zend.com/products/server/) (part of Zend Server package) * [Zend Optimizer+] (part of Zend Server package)
* [WinCache](http://www.iis.net/download/wincacheforphp) (extension for MS Windows Server) * [WinCache] (extension for MS Windows Server)
* [list of PHP accelerators on Wikipedia](http://en.wikipedia.org/wiki/List_of_PHP_accelerators) * [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

@@ -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 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 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 one real limitation of APCu is that it is tied to the server it's installed on. Memcached on the other hand is
as a separate service and can be accessed across the network, meaning that you can store objects in a hyper-fast data installed as a separate service and can be accessed across the network, meaning that you can store objects in a
store in a central location and many different systems can pull from it. 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 Note that when running PHP as a (Fast-)CGI application inside your webserver, every PHP process will have its own cache,
cache, i.e. APCu data is not shared between your worker processes. In these cases, you might want to consider using i.e. APCu data is not shared between your worker processes. In these cases, you might want to consider using memcached
memcached instead, as it's not tied to the PHP processes. 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 In a networked configuration APCu will usually outperform memcached in terms of access speed, but memcached will be
to scale up faster and further. If you do not expect to have multiple servers running your application, or do not need able to scale up faster and further. If you do not expect to have multiple servers running your application, or do not
the extra features that memcached offers then APCu is probably your best choice for object caching. need the extra features that memcached offers then APCu is probably your best choice for object caching.
Example logic using APCu: 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 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). 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) * [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/) * [Memcached](http://memcached.org/)
* [Redis](http://redis.io/) * [Redis](http://redis.io/)
* [XCache APIs](http://xcache.lighttpd.net/wiki/XcacheApi) * [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

@@ -5,9 +5,9 @@ title: Design Patterns
# 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 There are numerous ways to structure the code and project for your web application, and you can put as much or as
thought as you like into architecting. But it is usually a good idea to follow common patterns because it will make little thought as you like into architecting. But it is usually a good idea to follow common patterns because it will
your code easier to manage and easier for others to understand. make your code easier to manage and easier for others to understand.
* [Architectural pattern on Wikipedia](https://en.wikipedia.org/wiki/Architectural_pattern) * [Architectural pattern on Wikipedia](https://en.wikipedia.org/wiki/Architectural_pattern)
* [Software design pattern on Wikipedia](https://en.wikipedia.org/wiki/Software_design_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 ## Factory
One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the
the object you want to use. Consider the following example of the factory pattern: object you want to use. Consider the following example of the factory pattern:
{% highlight php %} {% highlight php %}
<?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 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 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 will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class.
class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in The second possible benefit is that if creating the object is a complicated job you can do all of the work in the
the factory, instead of repeating it every time you want to create a new instance. 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 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 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 ## Singleton
When designing web applications, it often makes sense conceptually and architecturally to allow access to one and When designing web applications, it often makes sense conceptually and architecturally to allow access to one and only
only one instance of a particular class. The singleton pattern enables us to do this. one instance of a particular class. The singleton pattern enables us to do this.
{% highlight php %} {% highlight php %}
<?php <?php
@@ -134,18 +134,24 @@ 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()`. 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: 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 constructor [`__construct()`](http://php.net/language.oop5.decon#object.construct) is declared as protected to
* 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. prevent creating a new instance outside of the class via the `new` 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). * The magic method [`__clone()`](http://php.net/language.oop5.cloning#object.clone) is declared as private to prevent
* 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. 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 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 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). 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 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 application, reducing testability. In most cases, dependency injection can (and should) be used in place of a singleton
singleton class. Using dependency injection means that we do not introduce unnecessary coupling into the design of our 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. 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) * [Singleton pattern on Wikipedia](https://en.wikipedia.org/wiki/Singleton_pattern)
@@ -153,11 +159,12 @@ application, as the object using the shared or global resource requires no knowl
## Strategy ## Strategy
With the strategy pattern you encapsulate specific families of algorithms allowing the client class responsible for 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. instantiating a particular algorithm to have no knowledge of the actual implementation. There are several variations on
There are several variations on the strategy pattern, the simplest of which is outlined below: 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 %} {% highlight php %}
<?php <?php
@@ -196,14 +203,14 @@ 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 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 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'. 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 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: behaviour required at runtime:
{% highlight php %} {% highlight php %}
<?php <?php
class SomeClient class SomeClient
{ {
private $output; 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' 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 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. that has been set.
{% highlight php %} {% highlight php %}
<?php <?php
$client = new SomeClient(); $client = new SomeClient();
// Want an array? // 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 ## 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). MVC is the most common architectural pattern used in the popular [PHP frameworks](https://github.com/codeguy/php-the-right-way/wiki/Frameworks).

View File

@@ -5,19 +5,19 @@ title: Functional Programming in PHP
# 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 PHP supports first-class functions, meaning that a function can be assigned to a variable. Both user-defined and
functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to other built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to
functions and a function can return other functions (a feature called higher-order functions). 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 Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code
is on iteration. focus is on iteration.
Anonymous functions (with support for closures) have been present since PHP 5.3 (2009). 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. 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 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. each array item.
@@ -45,8 +45,8 @@ A closure is an anonymous function that can access variables imported from the o
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. 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 In the next example we use closures to define a function returning a single filter function for `array_filter()`, out
a family of filter functions. of a family of filter functions.
{% highlight php %} {% highlight php %}
<?php <?php
@@ -80,8 +80,9 @@ defined to capture variables in scope and access them later when the anonymous f
* [Read about Anonymous functions][anonymous-functions] * [Read about Anonymous functions][anonymous-functions]
* [More details in the Closures RFC][closures-rfc] * [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 [closures-rfc]: https://wiki.php.net/rfc/closures
[call-user-func-array]: http://php.net/function.call-user-func-array

View File

@@ -33,8 +33,8 @@ if (strpos('testing', 'test') !== false) { // true, as strict comparison was
} }
{% endhighlight %} {% endhighlight %}
* [Comparison operators](http://php.net/manual/en/language.operators.comparison.php) * [Comparison operators](http://php.net/language.operators.comparison)
* [Comparison table](http://php.net/manual/en/types.comparisons.php) * [Comparison table](http://php.net/types.comparisons)
## Conditional statements ## Conditional statements
@@ -66,7 +66,7 @@ function test($a)
} }
{% endhighlight %} {% endhighlight %}
* [If statements](http://php.net/manual/en/control-structures.if.php) * [If statements](http://php.net/control-structures.if)
### Switch statements ### Switch statements
@@ -99,13 +99,13 @@ function test($a)
} }
{% endhighlight %} {% 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/) * [PHP switch](http://phpswitch.com/)
## Global namespace ## Global namespace
When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this, When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this, refer to
refer to the global function by using a backslash before the function name. the global function by using a backslash before the function name.
{% highlight php %} {% highlight php %}
<?php <?php
@@ -124,8 +124,8 @@ function array()
} }
{% endhighlight %} {% endhighlight %}
* [Global space](http://php.net/manual/en/language.namespaces.global.php) * [Global space](http://php.net/language.namespaces.global)
* [Global rules](http://php.net/manual/en/userlandnaming.rules.php) * [Global rules](http://php.net/userlandnaming.rules)
## Strings ## Strings
@@ -149,21 +149,21 @@ $a = 'Multi-line example' // concatenation operator (.)
. 'of what to do'; . 'of what to do';
{% endhighlight %} {% endhighlight %}
* [String Operators](http://php.net/manual/en/language.operators.string.php) * [String Operators](http://php.net/language.operators.string)
### String types ### String types
Strings are a series of characters, which should sound fairly simple. That said, there are a few different types Strings are a series of characters, which should sound fairly simple. That said, there are a few different types of
of strings and they offer slightly different syntax, with slightly different behaviors. strings and they offer slightly different syntax, with slightly different behaviors.
#### Single quotes #### Single quotes
Single quotes are used to denote a "literal string". Literal strings do not attempt to parse special characters Single quotes are used to denote a "literal string". Literal strings do not attempt to parse special characters or
or variables. variables.
If using single quotes, you could enter a variable name into a string like so: `'some $thing'`, and you would If using single quotes, you could enter a variable name into a string like so: `'some $thing'`, and you would see the
see the exact output of `some $thing`. If using double quotes, that would try to evaluate the `$thing` variable exact output of `some $thing`. If using double quotes, that would try to evaluate the `$thing` variable name and show
name and show errors if no variable was found. errors if no variable was found.
{% highlight php %} {% highlight php %}
@@ -177,7 +177,7 @@ echo 'This is my string, look at how pretty it is.'; // no need to parse a si
*/ */
{% endhighlight %} {% 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
@@ -204,8 +204,8 @@ $juice = 'plum';
echo "I like $juice juice"; // Output: I like plum juice echo "I like $juice juice"; // Output: I like plum juice
{% endhighlight %} {% endhighlight %}
When using interpolation, it is often the case that the variable will be touching another character. When using interpolation, it is often the case that the variable will be touching another character. This will result
This will result in some confusion as to what is the name of the variable, and what is a literal character. 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. 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 echo "I drank some juice made of {$juice[1]}s"; // $juice[1] will be parsed
{% endhighlight %} {% 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 #### Nowdoc syntax
@@ -253,7 +253,7 @@ EOD; // closing 'EOD' must be on it's own line, and to th
*/ */
{% endhighlight %} {% 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 #### Heredoc syntax
@@ -281,25 +281,25 @@ EOD; // closing 'EOD' must be on it's own line, and to th
*/ */
{% endhighlight %} {% 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? ### Which is quicker?
There is a myth floating around that single quote strings are fractionally quicker than double quote strings. This There is a myth floating around that single quote strings are fractionally quicker than double quote strings. This is
is fundamentally not true. fundamentally not true.
If you are defining a single string and not trying to concatenate values or anything complicated, then either a single or If you are defining a single string and not trying to concatenate values or anything complicated, then either a single
double quoted string will be entirely identical. Neither are quicker. 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 If you are concatenating multiple strings of any type, or interpolate values into a double quoted string, then the
vary. If you are working with a small number of values, concatenation is minutely faster. With a lot of values, interpolating results can vary. If you are working with a small number of values, concatenation is minutely faster. With a lot of
is minutely faster. 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. Regardless of what you are doing with strings, none of the types will ever have any noticable impact on your
Trying to rewrite code to use one or the other is always an exercise in futility, so avoid this micro-optimization unless you really application. Trying to rewrite code to use one or the other is always an exercise in futility, so avoid this micro-
understand the meaning and impact of the differences. 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 ## Ternary operators
@@ -334,7 +334,8 @@ return ($a == 5) ? 'yay' : 'nope'; // this example will return 'yay'
{% endhighlight %} {% 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 %} {% highlight php %}
<?php <?php
@@ -352,7 +353,8 @@ This can also be said for all operations(===, !==, !=, == etc).
#### Utilising brackets with ternary operators for form and function #### 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 %} {% highlight php %}
<?php <?php
@@ -361,12 +363,13 @@ return ($a == 3) ? "yay" : "nope"; // return yay or nope if $a == 3
// vs // vs
<?php
$a = 3; $a = 3;
return $a == 3 ? "yay" : "nope"; // return yay or nope if $a == 3 return $a == 3 ? "yay" : "nope"; // return yay or nope if $a == 3
{% endhighlight %} {% 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 %} {% highlight php %}
<?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; return ($a != 3 && $b != 4) || $c == 5;
{% endhighlight %} {% endhighlight %}
* [Ternary operators](http://php.net/manual/en/language.operators.comparison.php) * [Ternary operators](http://php.net/language.operators.comparison)
## Variable declarations ## Variable declarations
At times, coders attempt to make their code "cleaner" by declaring predefined variables with a different name. What 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 this does in reality is to double the memory consumption of said script. For the example below, let us say an example
an example string of text contains 1MB worth of data, by copying the variable you've increased the scripts execution to string of text contains 1MB worth of data, by copying the variable you've increased the scripts execution to 2MB.
2MB.
{% highlight php %} {% highlight php %}
<?php <?php