diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 23109f6..a795ab9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -109,3 +109,4 @@ All content is completely free now, and always will be. 3. Wrap all text to 120 characters 4. Code samples should adhere to PSR-1 or higher 5. Use [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/) for all content +6. Use language agnostic urls when refering to external websites such as the [php.net](http://php.net/urlhowto.php) manual diff --git a/_posts/01-02-01-Use-the-Current-Stable-Version.md b/_posts/01-02-01-Use-the-Current-Stable-Version.md index 53a004f..e83c7a6 100644 --- a/_posts/01-02-01-Use-the-Current-Stable-Version.md +++ b/_posts/01-02-01-Use-the-Current-Stable-Version.md @@ -1,12 +1,15 @@ --- -title: Use the Current Stable Version (5.6) +title: Use the Current Stable Version (5.6) isChild: true -anchor: use_the_current_stable_version +anchor: use_the_current_stable_version --- ## Use the Current Stable Version (5.6) {#use_the_current_stable_version_title} -If you are getting started with PHP, start with the current stable release of [PHP 5.6][php-release]. PHP has added powerful [new features](#language_highlights) over the last few years. Though the incremental version number difference between 5.2 and 5.6 is small, it represents _major_ improvements. If you are looking for a function or its usage, the documentation on the [php.net][php-docs] website will have the answer. +If you are getting started with PHP, start with the current stable release of [PHP 5.6][php-release]. PHP has added +powerful [new features](#language_highlights) over the last few years. Though the incremental version number difference +between 5.2 and 5.6 is small, it represents _major_ improvements. If you are looking for a function or its usage, the +documentation on the [php.net][php-docs] website will have the answer. -[php-release]: http://www.php.net/downloads.php -[php-docs]: http://www.php.net/manual/en/ +[php-release]: http://php.net/downloads.php +[php-docs]: http://php.net/manual/ diff --git a/_posts/01-03-01-Built-in-Web-Server.md b/_posts/01-03-01-Built-in-Web-Server.md index f33c002..6f611bd 100644 --- a/_posts/01-03-01-Built-in-Web-Server.md +++ b/_posts/01-03-01-Built-in-Web-Server.md @@ -1,15 +1,19 @@ --- -title: Built-in Web Server +title: Built-in Web Server isChild: true -anchor: builtin_web_server +anchor: builtin_web_server --- ## Built-in web server {#builtin_web_server_title} -With PHP 5.4 or newer, you can start learning PHP without installing and configuring a full-fledged web server. To start the server, run the following command from your terminal in your project's web root: +With PHP 5.4 or newer, you can start learning PHP without installing and configuring a full-fledged web server. +To start the server, run the following command from your terminal in your project's web root: - > php -S localhost:8000 +{% highlight console %} +> php -S localhost:8000 +{% endhighlight %} * [Learn about the built-in, command line web server][cli-server] -[cli-server]: http://www.php.net/manual/en/features.commandline.webserver.php + +[cli-server]: http://php.net/features.commandline.webserver diff --git a/_posts/01-04-01-Mac-Setup.md b/_posts/01-04-01-Mac-Setup.md index 815eb8e..0dceb5e 100644 --- a/_posts/01-04-01-Mac-Setup.md +++ b/_posts/01-04-01-Mac-Setup.md @@ -1,44 +1,46 @@ --- isChild: true -anchor: mac_setup +anchor: mac_setup --- -## Mac Setup {#mac_setup_title} +## Mac Setup {#mac_setup_title} -OS X comes prepackaged with PHP but it is normally a little behind the latest stable. Mountain Lion has -5.3.10, Mavericks has 5.4.17 and Yosemite has 5.5.9, but with PHP 5.6 out that is often not good enough. +OS X comes prepackaged with PHP but it is normally a little behind the latest stable. Mountain Lion has 5.3.10, +Mavericks has 5.4.17 and Yosemite has 5.5.9, but with PHP 5.6 out that is often not good enough. There are multiple ways to install PHP on OS X. ### Install PHP via Homebrew -[Homebrew](http://brew.sh/) is a powerful package manager for OS X, which can help you install PHP and -various extensions easily. [Homebrew PHP] is a repository that contains PHP-related "formulae" for Homebrew, -and will let you install PHP. +[Homebrew] is a powerful package manager for OS X, which can help you install PHP and various extensions easily. +[Homebrew PHP] is a repository that contains PHP-related "formulae" for Homebrew, and will let you install PHP. -At this point, you can install `php53`, `php54`, `php55` or `php56` using the `brew install` command, and switch between them by modifying your `PATH` variable. +At this point, you can install `php53`, `php54`, `php55` or `php56` using the `brew install` command, and switch +between them by modifying your `PATH` variable. ### Install PHP via phpbrew -[phpbrew] is a tool for installing and managing multiple PHP versions. This can be really useful if two -different applications/projects require different versions of PHP, and you are not using virtual machines. +[phpbrew] is a tool for installing and managing multiple PHP versions. This can be really useful if two different +applications/projects require different versions of PHP, and you are not using virtual machines. ### Compile from Source -Another option that gives you control over the version of PHP you install, is to [compile it yourself][mac-compile]. -In that case be sure to have installed either Xcode or Apple's substitute ["Command Line Tools for XCode"] -downloadable from Apple's Mac Developer Center. +Another option that gives you control over the version of PHP you install, is to [compile it yourself][mac-compile]. +In that case be sure to have installed either [Xcode][xcode-gcc-substitution] or Apple's substitute +["Command Line Tools for XCode"] downloadable from Apple's Mac Developer Center. -### All-in-One Installers +### All-in-One Installers + +The solutions listed above mainly handle PHP itself, and do not supply things like Apache, Nginx or a SQL server. +"All-in-one" solutions such as [MAMP][mamp-downloads] and [XAMPP][xampp] will install these other bits of software for +you and tie them all together, but ease of setup comes with a trade-off of flexibility. -The solutions listed above mainly handle PHP itself, and do not supply things like Apache, Nginx or a SQL server. "All-in-one" solutions such as [MAMP][mamp-downloads] and [XAMPP][xampp] will install these other bits of software for you and tie them all together, but ease of setup comes with a trade-off of flexibility. [Homebrew]: http://brew.sh/ [Homebrew PHP]: https://github.com/Homebrew/homebrew-php#installation -[mac-compile]: http://www.php.net/manual/en/install.macosx.compile.php +[phpbrew]: https://github.com/phpbrew/phpbrew +[mac-compile]: http://php.net/install.macosx.compile [xcode-gcc-substitution]: https://github.com/kennethreitz/osx-gcc-installer - ["Command Line Tools for XCode"]: https://developer.apple.com/downloads [mamp-downloads]: http://www.mamp.info/en/downloads/ -[phpbrew]: https://github.com/phpbrew/phpbrew [xampp]: http://www.apachefriends.org/en/xampp.html diff --git a/_posts/01-05-01-Windows-Setup.md b/_posts/01-05-01-Windows-Setup.md index 6094516..27fb89d 100644 --- a/_posts/01-05-01-Windows-Setup.md +++ b/_posts/01-05-01-Windows-Setup.md @@ -1,28 +1,30 @@ --- isChild: true -anchor: windows_setup +anchor: windows_setup --- ## Windows Setup {#windows_setup_title} -PHP is available in several ways for Windows. You can [download the binaries][php-downloads] and until recently you could use a '.msi' -installer. The installer is no longer supported and stops at PHP 5.3.0. +PHP is available in several ways for Windows. You can [download the binaries][php-downloads] and until recently you +could use a '.msi' installer. The installer is no longer supported and stops at PHP 5.3.0. -For learning and local development you can use the built in webserver with PHP 5.4+ so you don't need to worry about configuring it. If you -would like an "all-in-one" which includes a full-blown webserver and MySQL too then tools such as the [Web Platform Installer][wpi], -[Zend Server CE][zsce], [XAMPP][xampp], [EasyPHP][easyphp] and [WAMP][wamp] will help get a Windows development environment up and running fast. That said, these tools will be -a little different from production so be careful of environment differences if you are working on Windows and deploying to Linux. +For learning and local development you can use the built in webserver with PHP 5.4+ so you don't need to worry about +configuring it. If you would like an "all-in-one" which includes a full-blown webserver and MySQL too then tools such +as the [Web Platform Installer][wpi], [Zend Server CE][zsce], [XAMPP][xampp], [EasyPHP][easyphp] and [WAMP][wamp] will +help get a Windows development environment up and running fast. That said, these tools will be a little different from +production so be careful of environment differences if you are working on Windows and deploying to Linux. + +If you need to run your production system on Windows then IIS7 will give you the most stable and best performance. You +can use [phpmanager][phpmanager] (a GUI plugin for IIS7) to make configuring and managing PHP simple. IIS7 comes with +FastCGI built in and ready to go, you just need to configure PHP as a handler. For support and additional resources +there is a [dedicated area on iis.net][php-iis] for PHP. -If you need to run your production system on Windows then IIS7 will give you the most stable and best performance. You can use -[phpmanager][phpmanager] (a GUI plugin for IIS7) to make configuring and managing PHP simple. IIS7 comes with FastCGI built in and ready -to go, you just need to configure PHP as a handler. For support and additional resources there is a [dedicated area on iis.net][php-iis] for -PHP. [php-downloads]: http://windows.php.net -[phpmanager]: http://phpmanager.codeplex.com/ [wpi]: http://www.microsoft.com/web/downloads/platform.aspx [zsce]: http://www.zend.com/en/products/server-ce/ [xampp]: http://www.apachefriends.org/en/xampp.html [easyphp]: http://www.easyphp.org/ [wamp]: http://www.wampserver.com/en/ +[phpmanager]: http://phpmanager.codeplex.com/ [php-iis]: http://php.iis.net/ diff --git a/_posts/02-01-01-Code-Style-Guide.md b/_posts/02-01-01-Code-Style-Guide.md index 0ab5fd4..dbd7a49 100644 --- a/_posts/02-01-01-Code-Style-Guide.md +++ b/_posts/02-01-01-Code-Style-Guide.md @@ -2,21 +2,22 @@ anchor: code_style_guide --- -# Code Style Guide {#code_style_guide_title} +# Code Style Guide {#code_style_guide_title} The PHP community is large and diverse, composed of innumerable libraries, frameworks, and components. It is common for PHP developers to choose several of these and combine them into a single project. It is important that PHP code adhere (as close as possible) to a common code style to make it easy for developers to mix and match various libraries for their projects. -The [Framework Interop Group][fig] has proposed and approved a series of style recommendations. Not all of them related -to code-style, but those that do are [PSR-0][psr0], [PSR-1][psr1], [PSR-2][psr2] and [PSR-4][psr4]. These recommendations -are merely a set of rules that some projects like Drupal, Zend, Symfony, CakePHP, phpBB, AWS SDK, FuelPHP, Lithium, -etc are starting to adopt. You can use them for your own projects, or continue to use your own personal style. +The [Framework Interop Group][fig] has proposed and approved a series of style recommendations. Not all of them related +to code-style, but those that do are [PSR-0][psr0], [PSR-1][psr1], [PSR-2][psr2] and [PSR-4][psr4]. These +recommendations are merely a set of rules that some projects like Drupal, Zend, Symfony, CakePHP, phpBB, AWS SDK, +FuelPHP, Lithium, etc are starting to adopt. You can use them for your own projects, or continue to use your own +personal style. -Ideally you should write PHP code that adheres to a known standard. This could be any combination of PSR's, or one -of the coding standards made by PEAR or Zend. This means other developers can easily read and work with your code, -and applications that implement the components can have consistency even when working with lots of third-party code. +Ideally you should write PHP code that adheres to a known standard. This could be any combination of PSR's, or one +of the coding standards made by PEAR or Zend. This means other developers can easily read and work with your code, and +applications that implement the components can have consistency even when working with lots of third-party code. * [Read about PSR-0][psr0] * [Read about PSR-1][psr1] @@ -26,17 +27,18 @@ and applications that implement the components can have consistency even when wo * [Read about Zend Coding Standards][zend-cs] * [Read about Symfony Coding Standards][symfony-cs] -You can use [PHP_CodeSniffer][phpcs] to check code against any one of these recommendations, and plugins for text editors -like [Sublime Text 2][st-cs] to be given real time feedback. +You can use [PHP_CodeSniffer][phpcs] to check code against any one of these recommendations, and plugins for text +editors like [Sublime Text 2][st-cs] to be given real time feedback. You can fix the code layout automatically by using one of the two possible tools. One is Fabien Potencier's -[PHP Coding Standards Fixer][phpcsfixer] which has a very well tested codebase. It is bigger and slower, but very stable -and used by some huge projects like Magento and Symfony. Another option is [php.tools][phptools], which is made popular -by the [sublime-phpfmt][sublime-phpfmt] editor plugin. While being newer, it makes great improvements in performance, -meaning real-time editor fixing is more fluid. +[PHP Coding Standards Fixer][phpcsfixer] which has a very well tested codebase. It is bigger and slower, but very +stable and used by some huge projects like Magento and Symfony. Another option is [php.tools][phptools], which is made +popular by the [sublime-phpfmt][sublime-phpfmt] editor plugin. While being newer, it makes great improvements in +performance, meaning real-time editor fixing is more fluid. + +English is preferred for all symbol names and code infrastructure. Comments may be written in any language easily +readable by all current and future parties who may be working on the codebase. -English is preferred for all symbol names and code infrastructure. Comments may be written in any language easily readable -by all current and future parties who may be working on the codebase. [fig]: http://www.php-fig.org/ [psr0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md diff --git a/_posts/03-02-01-Programming-Paradigms.md b/_posts/03-02-01-Programming-Paradigms.md index 945a3f7..9271541 100644 --- a/_posts/03-02-01-Programming-Paradigms.md +++ b/_posts/03-02-01-Programming-Paradigms.md @@ -1,13 +1,13 @@ --- isChild: true -anchor: programming_paradigms +anchor: programming_paradigms --- ## Programming Paradigms {#programming_paradigms_title} PHP is a flexible, dynamic language that supports a variety of programming techniques. It has evolved dramatically over -the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in PHP 5.3 -(2009), and traits in PHP 5.4 (2012). +the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in +PHP 5.3 (2009), and traits in PHP 5.4 (2012). ### Object-oriented Programming @@ -19,12 +19,12 @@ interfaces, inheritance, constructors, cloning, exceptions, and more. ### Functional Programming -PHP supports first-class function, meaning that a function can be assigned to a variable. Both user-defined and built-in -functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to other -functions (feature called Higher-order functions) and function can return other functions. +PHP supports first-class function, meaning that a function can be assigned to a variable. Both user-defined and +built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to +other functions (feature called Higher-order functions) and function can return other functions. -Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code focus -on iteration. +Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code +focus on iteration. New anonymous functions (with support for closures) are present since PHP 5.3 (2009). @@ -36,7 +36,7 @@ can be used interchangeably with anonymous functions in almost all cases. * [Read about the Closure class][closure-class] * [More details in the Closures RFC][closures-rfc] * [Read about Callables][callables] -* [Read about dynamically invoking functions with `call_user_func_array`][call-user-func-array] +* [Read about dynamically invoking functions with `call_user_func_array()`][call-user-func-array] ### Meta Programming @@ -47,15 +47,17 @@ available as `__call()` and `__callStatic()`. * [Read about Magic Methods][magic-methods] * [Read about Reflection][reflection] +* [Read about Overloading][overloading] -[namespaces]: http://php.net/manual/en/language.namespaces.php -[overloading]: http://php.net/manual/en/language.oop5.overloading.php -[oop]: http://www.php.net/manual/en/language.oop5.php -[anonymous-functions]: http://www.php.net/manual/en/functions.anonymous.php -[closure-class]: http://php.net/manual/en/class.closure.php -[callables]: http://php.net/manual/en/language.types.callable.php -[magic-methods]: http://php.net/manual/en/language.oop5.magic.php -[reflection]: http://www.php.net/manual/en/intro.reflection.php -[traits]: http://www.php.net/traits -[call-user-func-array]: http://php.net/manual/en/function.call-user-func-array.php + +[oop]: http://php.net/language.oop5 +[traits]: http://php.net/language.oop5.traits +[anonymous-functions]: http://php.net/functions.anonymous +[closure-class]: http://php.net/class.closure [closures-rfc]: https://wiki.php.net/rfc/closures +[callables]: http://php.net/language.types.callable +[call-user-func-array]: http://php.net/function.call-user-func-array +[magic-methods]: http://php.net/language.oop5.magic +[reflection]: http://php.net/intro.reflection +[overloading]: http://php.net/language.oop5.overloading + diff --git a/_posts/03-03-01-Namespaces.md b/_posts/03-03-01-Namespaces.md index e22b968..dee41d7 100644 --- a/_posts/03-03-01-Namespaces.md +++ b/_posts/03-03-01-Namespaces.md @@ -1,34 +1,34 @@ --- isChild: true -anchor: namespaces +anchor: namespaces --- ## Namespaces {#namespaces_title} -As mentioned above, the PHP community has a lot of developers creating lots of code. This means that -one library's PHP code may use the same class name as another library. When both libraries are used -in the same namespace, they collide and cause trouble. +As mentioned above, the PHP community has a lot of developers creating lots of code. This means that one library's PHP +code may use the same class name as another library. When both libraries are used in the same namespace, they collide +and cause trouble. -_Namespaces_ solve this problem. As described in the PHP reference manual, namespaces may be compared -to operating system directories that _namespace_ files; two files with the same name may co-exist in -separate directories. Likewise, two PHP classes with the same name may co-exist in separate PHP -namespaces. It's as simple as that. +_Namespaces_ solve this problem. As described in the PHP reference manual, namespaces may be compared to operating +system directories that _namespace_ files; two files with the same name may co-exist in separate directories. Likewise, +two PHP classes with the same name may co-exist in separate PHP namespaces. It's as simple as that. -It is important for you to namespace your code so that it may be used by other developers without fear -of colliding with other libraries. +It is important for you to namespace your code so that it may be used by other developers without fear of colliding +with other libraries. -One recommended way to use namespaces is outlined in [PSR-0][psr0], which aims to provide a standard file, -class and namespace convention to allow plug-and-play code. +One recommended way to use namespaces is outlined in [PSR-0][psr0], which aims to provide a standard file, class and +namespace convention to allow plug-and-play code. -In December 2013 the PHP-FIG created a new autoloading standard: [PSR-4][psr4], which one day will -probably replace PSR-0. Currently both are still usable, as PSR-4 requires PHP 5.3 and many PHP 5.2-only -projects currently implement PSR-0. If you're going to use an autoloader standard for a new application or -package then you almost certainly want to look into PSR-4. +In December 2013 the PHP-FIG created a new autoloading standard: [PSR-4][psr4], which one day will probably replace +PSR-0. Currently both are still usable, as PSR-4 requires PHP 5.3 and many PHP 5.2-only projects currently implement +PSR-0. If you're going to use an autoloader standard for a new application or package then you almost certainly want +to look into PSR-4. * [Read about Namespaces][namespaces] * [Read about PSR-0][psr0] * [Read about PSR-4][psr4] -[namespaces]: http://php.net/manual/en/language.namespaces.php + +[namespaces]: http://php.net/language.namespaces [psr0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md -[psr4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md \ No newline at end of file +[psr4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md diff --git a/_posts/03-04-01-Standard-PHP-Library.md b/_posts/03-04-01-Standard-PHP-Library.md index 3ce419a..a81e7c5 100644 --- a/_posts/03-04-01-Standard-PHP-Library.md +++ b/_posts/03-04-01-Standard-PHP-Library.md @@ -1,13 +1,16 @@ --- title: Standard PHP Library isChild: true -anchor: standard_php_library +anchor: standard_php_library --- ## Standard PHP Library {#standard_php_library_title} -The Standard PHP Library (SPL) is packaged with PHP and provides a collection of classes and interfaces. It is made up primarily of commonly needed datastructure classes (stack, queue, heap, and so on), and iterators which can traverse over these datastructures or your own classes which implement SPL interfaces. +The Standard PHP Library (SPL) is packaged with PHP and provides a collection of classes and interfaces. It is made up +primarily of commonly needed datastructure classes (stack, queue, heap, and so on), and iterators which can traverse +over these datastructures or your own classes which implement SPL interfaces. * [Read about the SPL][spl] -[spl]: http://php.net/manual/en/book.spl.php + +[spl]: http://php.net/book.spl diff --git a/_posts/03-05-01-Command-Line-Interface.md b/_posts/03-05-01-Command-Line-Interface.md index d5d9af4..5bc19e6 100644 --- a/_posts/03-05-01-Command-Line-Interface.md +++ b/_posts/03-05-01-Command-Line-Interface.md @@ -1,23 +1,26 @@ --- isChild: true -anchor: command_line_interface +anchor: command_line_interface --- ## Command Line Interface {#command_line_interface_title} -PHP was created to write web applications, but is also useful for scripting command line interface (CLI) programs. Command line PHP programs can help automate common tasks like testing, deployment, and application administrivia. +PHP was created to write web applications, but is also useful for scripting command line interface (CLI) programs. +Command line PHP programs can help automate common tasks like testing, deployment, and application administrivia. -CLI PHP programs are powerful because you can use your app's code directly without having to create and secure a web GUI for it. Just be sure not to put your CLI PHP scripts in your public web root! +CLI PHP programs are powerful because you can use your app's code directly without having to create and secure a web +GUI for it. Just be sure not to put your CLI PHP scripts in your public web root! Try running PHP from your command line: -{% highlight bash %} +{% highlight console %} > php -i {% endhighlight %} -The `-i` option will print your PHP configuration just like the [`phpinfo`][phpinfo] function. +The `-i` option will print your PHP configuration just like the [`phpinfo()`][phpinfo] function. -The `-a` option provides an interactive shell, similar to ruby's IRB or python's interactive shell. There are a number of other useful [command line options][cli-options], too. +The `-a` option provides an interactive shell, similar to ruby's IRB or python's interactive shell. There are a number +of other useful [command line options][cli-options], too. Let's write a simple "Hello, $name" CLI program. To try it out, create a file named `hello.php`, as below. @@ -31,13 +34,16 @@ $name = $argv[1]; echo "Hello, $name\n"; {% endhighlight %} -PHP sets up two special variables based on the arguments your script is run with. [`$argc`][argc] is an integer variable containing the argument *count* and [`$argv`][argv] is an array variable containing each argument's *value*. The first argument is always the name of your PHP script file, in this case `hello.php`. +PHP sets up two special variables based on the arguments your script is run with. [`$argc`][argc] is an integer +variable containing the argument *count* and [`$argv`][argv] is an array variable containing each argument's *value*. +The first argument is always the name of your PHP script file, in this case `hello.php`. -The `exit()` expression is used with a non-zero number to let the shell know that the command failed. Commonly used exit codes can be found [here][exit-codes] +The `exit()` expression is used with a non-zero number to let the shell know that the command failed. Commonly used +exit codes can be found [here][exit-codes]. To run our script, above, from the command line: -{% highlight bash %} +{% highlight console %} > php hello.php Usage: php hello.php [name] > php hello.php world @@ -48,10 +54,11 @@ Hello, world * [Learn about running PHP from the command line][php-cli] * [Learn about setting up Windows to run PHP from the command line][php-cli-windows] -[phpinfo]: http://php.net/manual/en/function.phpinfo.php -[cli-options]: http://www.php.net/manual/en/features.commandline.options.php -[argc]: http://php.net/manual/en/reserved.variables.argc.php -[argv]: http://php.net/manual/en/reserved.variables.argv.php -[php-cli]: http://php.net/manual/en/features.commandline.php -[php-cli-windows]: http://www.php.net/manual/en/install.windows.commandline.php -[exit-codes]: http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits + +[phpinfo]: http://php.net/function.phpinfo +[cli-options]: http://php.net/features.commandline.options +[argc]: http://php.net/reserved.variables.argc +[argv]: http://php.net/reserved.variables.argv +[exit-codes]: http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits +[php-cli]: http://php.net/features.commandline +[php-cli-windows]: http://php.net/install.windows.commandline diff --git a/_posts/03-06-01-XDebug.md b/_posts/03-06-01-XDebug.md index 0f0622b..6ac4a54 100644 --- a/_posts/03-06-01-XDebug.md +++ b/_posts/03-06-01-XDebug.md @@ -1,27 +1,29 @@ --- title: XDebug isChild: true -anchor: xdebug +anchor: xdebug --- ## XDebug {#xdebug_title} One of the most useful tools in software development is a proper debugger. It allows you to trace the execution of your code and monitor the contents of the stack. XDebug, PHP's debugger, can be utilized by various IDEs to provide -Breakpoints and stack inspection. It can also allow tools like PHPUnit and KCacheGrind to perform code coverage analysis -and code profiling. +Breakpoints and stack inspection. It can also allow tools like PHPUnit and KCacheGrind to perform code coverage +analysis and code profiling. -If you find yourself in a bind, willing to resort to var_dump/print_r, and you still can't find the solution - maybe you -need to use the debugger. +If you find yourself in a bind, willing to resort to `var_dump()`/`print_r()`, and you still can't find the solution - +maybe you need to use the debugger. -[Installing XDebug][xdebug-install] can be tricky, but one of its most important features is "Remote Debugging" - if you -develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you will -want to enable right away. +[Installing XDebug][xdebug-install] can be tricky, but one of its most important features is "Remote Debugging" - if +you develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you +will want to enable right away. Traditionally, you will modify your Apache VHost or .htaccess file with these values: - php_value xdebug.remote_host=192.168.?.? - php_value xdebug.remote_port=9000 +{% highlight ini %} +php_value xdebug.remote_host=192.168.?.? +php_value xdebug.remote_port=9000 +{% endhighlight %} The "remote host" and "remote port" will correspond to your local computer and the port that you configure your IDE to listen on. Then it's just a matter of putting your IDE into "listen for connections" mode, and loading the URL: @@ -31,13 +33,14 @@ listen on. Then it's just a matter of putting your IDE into "listen for connecti Your IDE will now intercept the current state as the script executes, allowing you to set breakpoints and probe the values in memory. -Graphical debuggers make it very easy to step through code, inspect variables, and eval code against the live runtime. -Many IDE's have built-in or plugin-based support for graphical debugging with xdebug. MacGDBp is a free, open-source, +Graphical debuggers make it very easy to step through code, inspect variables, and eval code against the live runtime. +Many IDE's have built-in or plugin-based support for graphical debugging with xdebug. MacGDBp is a free, open-source, stand-alone xdebug GUI for Mac. * [Learn more about XDebug][xdebug-docs] * [Learn more about MacGDBp][macgdbp-install] -[xdebug-docs]: http://xdebug.org/docs/ + [xdebug-install]: http://xdebug.org/docs/install +[xdebug-docs]: http://xdebug.org/docs/ [macgdbp-install]: http://www.bluestatic.org/software/macgdbp/ diff --git a/_posts/04-01-01-Dependency-Management.md b/_posts/04-01-01-Dependency-Management.md index 95be994..19eeb0e 100644 --- a/_posts/04-01-01-Dependency-Management.md +++ b/_posts/04-01-01-Dependency-Management.md @@ -4,11 +4,16 @@ anchor: dependency_management # Dependency Management {#dependency_management_title} -There are a ton of PHP libraries, frameworks, and components to choose from. Your project will likely use several of them — these are project dependencies. Until recently, PHP did not have a good way to manage these project dependencies. Even if you managed them manually, you still had to worry about autoloaders. No more. +There are a ton of PHP libraries, frameworks, and components to choose from. Your project will likely use several of +them — these are project dependencies. Until recently, PHP did not have a good way to manage these project +dependencies. Even if you managed them manually, you still had to worry about autoloaders. No more. -Currently there are two major package management systems for PHP - Composer and PEAR. Which one is right for you? The answer is both. +Currently there are two major package management systems for PHP - Composer and PEAR. Which one is right for you? The +answer is both. - * Use **Composer** when managing dependencies for a single project. - * Use **PEAR** when managing dependencies for PHP as a whole on your system. +* Use **Composer** when managing dependencies for a single project. +* Use **PEAR** when managing dependencies for PHP as a whole on your system. -In general, Composer packages will be available only in the projects that you explicitly specify whereas a PEAR package would be available to all of your PHP projects. While PEAR might sound like the easier approach at first glance, there are advantages to using a project-by-project approach to your dependencies. +In general, Composer packages will be available only in the projects that you explicitly specify whereas a PEAR package +would be available to all of your PHP projects. While PEAR might sound like the easier approach at first glance, there +are advantages to using a project-by-project approach to your dependencies. diff --git a/_posts/04-02-01-Composer-and-Packagist.md b/_posts/04-02-01-Composer-and-Packagist.md index 79bd1e1..77b8245 100644 --- a/_posts/04-02-01-Composer-and-Packagist.md +++ b/_posts/04-02-01-Composer-and-Packagist.md @@ -1,28 +1,40 @@ --- isChild: true -anchor: composer_and_packagist +anchor: composer_and_packagist --- ## Composer and Packagist {#composer_and_packagist_title} -Composer is a **brilliant** dependency manager for PHP. List your project's dependencies in a `composer.json` file and, with a few simple commands, Composer will automatically download your project's dependencies and setup autoloading for you. +Composer is a **brilliant** dependency manager for PHP. List your project's dependencies in a `composer.json` file and, +with a few simple commands, Composer will automatically download your project's dependencies and setup autoloading for +you. -There are already a lot of PHP libraries that are compatible with Composer, ready to be used in your project. These "packages" are listed on [Packagist][1], the official repository for Composer-compatible PHP libraries. +There are already a lot of PHP libraries that are compatible with Composer, ready to be used in your project. These +"packages" are listed on [Packagist][1], the official repository for Composer-compatible PHP libraries. ### How to Install Composer -You can install Composer locally (in your current working directory; though this is no longer recommended) or globally (e.g. /usr/local/bin). Let's assume you want to install Composer locally. From your project's root directory: +You can install Composer locally (in your current working directory; though this is no longer recommended) or globally +(e.g. /usr/local/bin). Let's assume you want to install Composer locally. From your project's root directory: - curl -s https://getcomposer.org/installer | php +{% highlight console %} +curl -s https://getcomposer.org/installer | php +{% endhighlight %} -This will download `composer.phar` (a PHP binary archive). You can run this with `php` to manage your project dependencies. Please Note: 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. +Please Note: If you pipe downloaded code directly into an interpreter, please read the +code online first to confirm it is safe. #### Installing on Windows -For Windows users the easiest way to get up and running is to use the [ComposerSetup][6] installer, which performs a global install and sets up your `$PATH` so that you can just call `composer` from any directory in your command line. +For Windows users the easiest way to get up and running is to use the [ComposerSetup][6] installer, which performs a +global install and sets up your `$PATH` so that you can just call `composer` from any directory in your command line. ### How to Install Composer (manually) -Manually installing Composer is an advanced technique; however, there are various reasons why a developer might prefer this method vs. using the interactive installation routine. The interactive installation checks your PHP installation to ensure that: +Manually installing Composer is an advanced technique; however, there are various reasons why a developer might prefer +this method vs. using the interactive installation routine. The interactive installation checks your PHP installation +to ensure that: - a sufficient version of PHP is being used - `.phar` files can be executed correctly @@ -30,30 +42,47 @@ Manually installing Composer is an advanced technique; however, there are variou - certain problematic extensions are not loaded - certain `php.ini` settings are set -Since a manual installation performs none of these checks, you have to decide whether the trade-off is worth it for you. As such, below is how to obtain Composer manually: +Since a manual installation performs none of these checks, you have to decide whether the trade-off is worth it for +you. As such, below is how to obtain Composer manually: - curl -s https://getcomposer.org/composer.phar -o $HOME/local/bin/composer - chmod +x $HOME/local/bin/composer +{% highlight console %} +curl -s https://getcomposer.org/composer.phar -o $HOME/local/bin/composer +chmod +x $HOME/local/bin/composer +{% endhighlight %} -The path `$HOME/local/bin` (or a directory of your choice) should be in your `$PATH` environment variable. This will result in a `composer` command being available. +The path `$HOME/local/bin` (or a directory of your choice) should be in your `$PATH` environment variable. This will +result in a `composer` command being available. -When you come across documentation that states to run Composer as `php composer.phar install`, you can substitute that with: +When you come across documentation that states to run Composer as `php composer.phar install`, you can substitute that +with: + +{% highlight console %} +composer install +{% endhighlight %} - composer install - This section will assume you have installed composer globally. ### How to Define and Install Dependencies -Composer keeps track of your project's dependencies in a file called `composer.json`. You can manage it by hand if you like, or use Composer itself. The `composer require` command adds a project dependency and if you don't have a `composer.json` file, one will be created. Here's an example that adds [Twig][2] as a dependency of your project. +Composer keeps track of your project's dependencies in a file called `composer.json`. You can manage it by hand if you +like, or use Composer itself. The `composer require` command adds a project dependency and if you don't have a +`composer.json` file, one will be created. Here's an example that adds [Twig][2] as a dependency of your project. - composer require twig/twig:~1.8 +{% highlight console %} +composer require twig/twig:~1.8 +{% endhighlight %} -Alternatively the `composer init` command will guide you through creating a full `composer.json` file for your project. Either way, once you've created your `composer.json` file you can tell Composer to download and install your dependencies into the `vendors/` directory. This also applies to projects you've downloaded that already provide a `composer.json` file: +Alternatively the `composer init` command will guide you through creating a full `composer.json` file for your project. +Either way, once you've created your `composer.json` file you can tell Composer to download and install your +dependencies into the `vendor/` directory. This also applies to projects you've downloaded that already provide a +`composer.json` file: - composer install +{% highlight console %} +composer install +{% endhighlight %} -Next, add this line to your application's primary PHP file; this will tell PHP to use Composer's autoloader for your project dependencies. +Next, add this line to your application's primary PHP file; this will tell PHP to use Composer's autoloader for your +project dependencies. {% highlight php %} pear-channel/Package -The "pear" prefix is hardcoded to avoid any conflicts, as a pear channel could be the same as another packages vendor name for example, then the channel short name (or full URL) can be used -to reference which channel the package is in. +The "pear" prefix is hardcoded to avoid any conflicts, as a pear channel could be the same as another packages vendor +name for example, then the channel short name (or full URL) can be used to reference which channel the package is in. -When this code is installed it will be available in your vendor directory and automatically -available through the Composer autoloader: +When this code is installed it will be available in your vendor directory and automatically available through the +Composer autoloader: > vendor/pear-pear2.php.net/PEAR2_HTTP_Request/pear2/HTTP/Request.php To use this PEAR package simply reference it like so: {% highlight php %} +format('Y-m-d') . "\n"; {% endhighlight %} Calculating with DateTime is possible with the DateInterval class. DateTime has methods like `add()` and `sub()` that take a DateInterval as an argument. Do not write code that expect same number of seconds in every day, both daylight -saving and timezone alterations will break that assumption. Use date intervals instead. To calculate date difference use -the `diff()` method. It will return new DateInterval, which is super easy to display. +saving and timezone alterations will break that assumption. Use date intervals instead. To calculate date difference +use the `diff()` method. It will return new DateInterval, which is super easy to display. + {% highlight php %} add(new \DateInterval('P1M6D')); +$end->add(new DateInterval('P1M6D')); $diff = $end->diff($start); echo 'Difference: ' . $diff->format('%m month, %d days (total: %a days)') . "\n"; @@ -36,6 +38,7 @@ echo 'Difference: ' . $diff->format('%m month, %d days (total: %a days)') . "\n" {% endhighlight %} On DateTime objects you can use standard comparison: + {% highlight php %} format('Y-m-d') . ' '; @@ -59,5 +63,5 @@ foreach ($periodIterator as $date) { * [Read about DateTime][datetime] * [Read about date formatting][dateformat] (accepted date format string options) -[datetime]: http://www.php.net/manual/book.datetime.php -[dateformat]: http://www.php.net/manual/function.date.php +[datetime]: http://php.net/book.datetime +[dateformat]: http://php.net/function.date diff --git a/_posts/05-04-01-Design-Patterns.md b/_posts/05-04-01-Design-Patterns.md index 3f6a032..4131503 100644 --- a/_posts/05-04-01-Design-Patterns.md +++ b/_posts/05-04-01-Design-Patterns.md @@ -1,6 +1,6 @@ --- isChild: true -anchor: design_patterns +anchor: design_patterns --- ## Design Patterns {#design_patterns_title} diff --git a/_posts/05-05-01-PHP-and-UTF8.md b/_posts/05-05-01-PHP-and-UTF8.md index d3e2c95..0066fba 100644 --- a/_posts/05-05-01-PHP-and-UTF8.md +++ b/_posts/05-05-01-PHP-and-UTF8.md @@ -1,7 +1,7 @@ --- -title: Working with UTF-8 +title: Working with UTF-8 isChild: true -anchor: php_and_utf8 +anchor: php_and_utf8 --- ## Working with UTF-8 {#php_and_utf8_title} @@ -11,60 +11,63 @@ _This section was originally written by [Alex Cabal](https://alexcabal.com/) ove ### There's no one-liner. Be careful, detailed, and consistent. -Right now PHP does not support Unicode at a low level. There are ways to ensure that UTF-8 strings are processed OK, -but it's not easy, and it requires digging in to almost all levels of the web app, from HTML to SQL to PHP. We'll aim +Right now PHP does not support Unicode at a low level. There are ways to ensure that UTF-8 strings are processed OK, +but it's not easy, and it requires digging in to almost all levels of the web app, from HTML to SQL to PHP. We'll aim for a brief, practical summary. ### UTF-8 at the PHP level -The basic string operations, like concatenating two strings and assigning strings to variables, don't need anything -special for UTF-8. However most string functions, like `strpos()` and `strlen()`, do need special consideration. These -functions often have an `mb_*` counterpart: for example, `mb_strpos()` and `mb_strlen()`. These `mb_*` strings are made +The basic string operations, like concatenating two strings and assigning strings to variables, don't need anything +special for UTF-8. However most string functions, like `strpos()` and `strlen()`, do need special consideration. These +functions often have an `mb_*` counterpart: for example, `mb_strpos()` and `mb_strlen()`. These `mb_*` strings are made available to you via the [Multibyte String Extension], and are specifically designed to operate on Unicode strings. -You must use the `mb_*` functions whenever you operate on a Unicode string. For example, if you use `substr()` on a -UTF-8 string, there's a good chance the result will include some garbled half-characters. The correct function to use +You must use the `mb_*` functions whenever you operate on a Unicode string. For example, if you use `substr()` on a +UTF-8 string, there's a good chance the result will include some garbled half-characters. The correct function to use would be the multibyte counterpart, `mb_substr()`. -The hard part is remembering to use the `mb_*` functions at all times. If you forget even just once, your Unicode +The hard part is remembering to use the `mb_*` functions at all times. If you forget even just once, your Unicode string has a chance of being garbled during further processing. -Not all string functions have an `mb_*` counterpart. If there isn't one for what you want to do, then you might be out +Not all string functions have an `mb_*` counterpart. If there isn't one for what you want to do, then you might be out of luck. -You should use the `mb_internal_encoding()` function at the top of every PHP script you write (or at the -top of your global include script), and the `mb_http_output()` function right after it if your script is outputting to -a browser. Explicitly defining the encoding of your strings in every script will save you a lot of headaches down the -road. +You should use the `mb_internal_encoding()` function at the top of every PHP script you write (or at the top of your +global include script), and the `mb_http_output()` function right after it if your script is outputting to a browser. +Explicitly defining the encoding of your strings in every script will save you a lot of headaches down the road. -Additionally, many PHP functions that operate on strings have an optional parameter letting you specify the character -encoding. You should always explicitly indicate UTF-8 when given the option. For example, `htmlentities()` has an -option for character encoding, and you should always specify UTF-8 if dealing with such strings. Note that as of PHP 5.4.0, UTF-8 is the default encoding for `htmlentities()` and `htmlspecialchars()`. +Additionally, many PHP functions that operate on strings have an optional parameter letting you specify the character +encoding. You should always explicitly indicate UTF-8 when given the option. For example, `htmlentities()` has an +option for character encoding, and you should always specify UTF-8 if dealing with such strings. Note that as of PHP 5. +4.0, UTF-8 is the default encoding for `htmlentities()` and `htmlspecialchars()`. Finally, If you are building an distributed application and cannot be certain that the `mbstring` extension will be -enabled, then consider using the [patchwork/utf8] Composer package. This -will use `mbstring` if it is available, and fall back to non UTF-8 functions if not. +enabled, then consider using the [patchwork/utf8] Composer package. This will use `mbstring` if it is available, and +fall back to non UTF-8 functions if not. -[Multibyte String Extension]: http://php.net/manual/en/book.mbstring.php +[Multibyte String Extension]: http://php.net/book.mbstring [patchwork/utf8]: https://packagist.org/packages/patchwork/utf8 ### UTF-8 at the Database level -If your PHP script accesses MySQL, there's a chance your strings could be stored as non-UTF-8 strings in the database +If your PHP script accesses MySQL, there's a chance your strings could be stored as non-UTF-8 strings in the database even if you follow all of the precautions above. -To make sure your strings go from PHP to MySQL as UTF-8, make sure your database and tables are all set to the -`utf8mb4` character set and collation, and that you use the `utf8mb4` character set in the PDO connection string. See +To make sure your strings go from PHP to MySQL as UTF-8, make sure your database and tables are all set to the +`utf8mb4` character set and collation, and that you use the `utf8mb4` character set in the PDO connection string. See example code below. This is _critically important_. -Note that you must use the `utf8mb4` character set for complete UTF-8 support, not the `utf8` character set! See +Note that you must use the `utf8mb4` character set for complete UTF-8 support, not the `utf8` character set! See Further Reading for why. ### UTF-8 at the browser level -Use the `mb_http_output()` function to ensure that your PHP script outputs UTF-8 strings to your browser. +Use the `mb_http_output()` function to ensure that your PHP script outputs UTF-8 strings to your browser. -The browser will then need to be told by the HTTP response that this page should be considered as UTF-8. The historic approach to doing that was to include the [charset `` tag](http://htmlpurifier.org/docs/enduser-utf8.html) in your page's `
` 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 `` tag](http://htmlpurifier.org/docs/enduser-utf8.html) in +your page's `` 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 %} \PDO::ERRMODE_EXCEPTION, - \PDO::ATTR_PERSISTENT => false + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_PERSISTENT => false ) ); @@ -128,20 +131,21 @@ header('Content-Type: text/html; charset=UTF-8'); ### Further reading -* [PHP Manual: String Operations](http://php.net/manual/en/language.operators.string.php) -* [PHP Manual: String Functions](http://php.net/manual/en/ref.strings.php) - * [`strpos()`](http://php.net/manual/en/function.strpos.php) - * [`strlen()`](http://php.net/manual/en/function.strlen.php) - * [`substr()`](http://php.net/manual/en/function.substr.php) -* [PHP Manual: Multibyte String Functions](http://php.net/manual/en/ref.mbstring.php) - * [`mb_strpos()`](http://php.net/manual/en/function.mb-strpos.php) - * [`mb_strlen()`](http://php.net/manual/en/function.mb-strlen.php) - * [`mb_substr()`](http://php.net/manual/en/function.mb-substr.php) - * [`mb_internal_encoding()`](http://php.net/manual/en/function.mb-internal-encoding.php) - * [`mb_http_output()`](http://php.net/manual/en/function.mb-http-output.php) - * [`htmlentities()`](http://php.net/manual/en/function.htmlentities.php) - * [`htmlspecialchars()`](http://www.php.net/manual/en/function.htmlspecialchars.php) +* [PHP Manual: String Operations](http://php.net/language.operators.string) +* [PHP Manual: String Functions](http://php.net/ref.strings) + * [`strpos()`](http://php.net/function.strpos) + * [`strlen()`](http://php.net/function.strlen) + * [`substr()`](http://php.net/function.substr) +* [PHP Manual: Multibyte String Functions](http://php.net/ref.mbstring) + * [`mb_strpos()`](http://php.net/function.mb-strpos) + * [`mb_strlen()`](http://php.net/function.mb-strlen) + * [`mb_substr()`](http://php.net/function.mb-substr) + * [`mb_internal_encoding()`](http://php.net/function.mb-internal-encoding) + * [`mb_http_output()`](http://php.net/function.mb-http-output) + * [`htmlentities()`](http://php.net/function.htmlentities) + * [`htmlspecialchars()`](http://php.net/function.htmlspecialchars) * [PHP UTF-8 Cheatsheet](http://blog.loftdigital.com/blog/php-utf-8-cheatsheet) +* [Handling UTF-8 with PHP](http://www.phpwact.org/php/i18n/utf-8) * [Stack Overflow: What factors make PHP Unicode-incompatible?](http://stackoverflow.com/questions/571694/what-factors-make-php-unicode-incompatible) * [Stack Overflow: Best practices in PHP and MySQL with international strings](http://stackoverflow.com/questions/140728/best-practices-in-php-and-mysql-with-international-strings) * [How to support full Unicode in MySQL databases](http://mathiasbynens.be/notes/mysql-utf8mb4) diff --git a/_posts/06-01-01-Dependency-Injection.md b/_posts/06-01-01-Dependency-Injection.md index f3e1ccb..de77179 100644 --- a/_posts/06-01-01-Dependency-Injection.md +++ b/_posts/06-01-01-Dependency-Injection.md @@ -1,5 +1,5 @@ --- -title: Dependency Injection +title: Dependency Injection anchor: dependency_injection --- @@ -10,5 +10,6 @@ From [Wikipedia](http://en.wikipedia.org/wiki/Dependency_injection): > Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it > possible to change them, whether at run-time or compile-time. -This quote makes the concept sound much more complicated than it actually is. Dependency Injection is providing a component -with its dependencies either through constructor injection, method calls or the setting of properties. It is that simple. +This quote makes the concept sound much more complicated than it actually is. Dependency Injection is providing a +component with its dependencies either through constructor injection, method calls or the setting of properties. It is +that simple. diff --git a/_posts/06-02-01-Basic-Concept.md b/_posts/06-02-01-Basic-Concept.md index cc2eca7..5469450 100644 --- a/_posts/06-02-01-Basic-Concept.md +++ b/_posts/06-02-01-Basic-Concept.md @@ -1,15 +1,15 @@ --- isChild: true -anchor: basic_concept +anchor: basic_concept --- ## Basic Concept {#basic_concept_title} We can demonstrate the concept with a simple, yet naive example. -Here we have a `Database` class that requires an adapter to speak to the database. We instantiate the -adapter in the constructor and create a hard dependency. This makes testing difficult and means the `Database` class is -very tightly coupled to the adapter. +Here we have a `Database` class that requires an adapter to speak to the database. We instantiate the adapter in the +constructor and create a hard dependency. This makes testing difficult and means the `Database` class is very tightly +coupled to the adapter. {% highlight php %} 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 %} -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 %} -prepare('SELECT name FROM users WHERE id = :id'); -$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); // <-- Automatically sanitized by PDO -$stmt->execute(); -{% endhighlight %} - -This is correct code. It uses a bound parameter on a PDO statement. This escapes the foreign input ID before it is introduced to the -database preventing potential SQL injection attacks. - -* [Learn about PDO] - -You should also be aware that database connections use up resources and it was not unheard-of to have resources -exhausted if connections were not implicitly closed, however this was more common in other languages. Using PDO you -can implicitly close the connection by destroying the object by ensuring all remaining references to it are deleted, -i.e. set to NULL. If you don't do this explicitly, PHP will automatically close the connection when your script ends - -unless of course you are using persistent connections. - -* [Learn about PDO connections] - -[Learn about PDO]: http://www.php.net/manual/en/book.pdo.php -[Learn about PDO connections]: http://php.net/manual/en/pdo.connections.php -[officially deprecated as of PHP 5.5.0]: http://php.net/manual/en/migration55.deprecated.php -[SQL Injection]: http://wiki.hashphp.org/Validation - -[pdo]: http://php.net/pdo -[mysql]: http://php.net/mysql [mysqli]: http://php.net/mysqli [pgsql]: http://php.net/pgsql [mssql]: http://php.net/mssql diff --git a/_posts/07-02-01-Databases_MySQL.md b/_posts/07-02-01-Databases_MySQL.md new file mode 100644 index 0000000..362cd88 --- /dev/null +++ b/_posts/07-02-01-Databases_MySQL.md @@ -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 diff --git a/_posts/07-03-01-Abstraction-Layers.md b/_posts/07-03-01-Abstraction-Layers.md deleted file mode 100644 index c52554a..0000000 --- a/_posts/07-03-01-Abstraction-Layers.md +++ /dev/null @@ -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 diff --git a/_posts/07-03-01-Databases_PDO.md b/_posts/07-03-01-Databases_PDO.md new file mode 100644 index 0000000..739b605 --- /dev/null +++ b/_posts/07-03-01-Databases_PDO.md @@ -0,0 +1,74 @@ +--- +isChild: true +title: PDO Extension +anchor: pdo_extension +--- + +## PDO Extension {#pdo_extension_title} + +[PDO] is a database connection abstraction library — built into PHP since 5.1.0 — 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 %} +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 %} +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 %} +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 diff --git a/_posts/07-02-01-Interacting-via-Code.md b/_posts/07-04-01-Interacting-via-Code.md similarity index 68% rename from _posts/07-02-01-Interacting-via-Code.md rename to _posts/07-04-01-Interacting-via-Code.md index 4ee31d6..0c2107d 100644 --- a/_posts/07-02-01-Interacting-via-Code.md +++ b/_posts/07-04-01-Interacting-via-Code.md @@ -1,12 +1,12 @@ --- isChild: true -title: Interacting with Databases -anchor: databases_interacting +title: Interacting with Databases +anchor: databases_interacting --- ## Interacting with Databases {#databases_interacting_title} -When developers first start to learn PHP, they often end up mixing their database interaction up with their +When developers first start to learn PHP, they often end up mixing their database interaction up with their presentation logic, using code that might look like this: {% highlight php %} @@ -19,9 +19,11 @@ foreach ($db->query('SELECT * FROM table') as $row) { {% endhighlight %} -This is bad practice for all sorts of reasons, mainly that its hard to debug, hard to test, hard to read and it is going to output a lot of fields if you don't put a limit on there. +This is bad practice for all sorts of reasons, mainly that its hard to debug, hard to test, hard to read and it is +going to output a lot of fields if you don't put a limit on there. -While there are many other solutions to doing this - depending on if you prefer [OOP](/#object-oriented-programming) or [functional programming](/#functional-programming) - there must be some element of separation. +While there are many other solutions to doing this - depending on if you prefer [OOP](/#object-oriented-programming) or +[functional programming](/#functional-programming) - there must be some element of separation. Consider the most basic step: @@ -38,13 +40,14 @@ foreach (getAllFoos($db) as $row) { That is a good start. Put those two items in two different files and you've got some clean separation. -Create a class to place that method in and you have a "Model". Create a simple `.php` file to put the presentation logic in and you have a "View", which is very nearly [MVC] - a common OOP architecture for most [frameworks](/#frameworks_title). +Create a class to place that method in and you have a "Model". Create a simple `.php` file to put the presentation +logic in and you have a "View", which is very nearly [MVC] - a common OOP architecture for most +[frameworks](/#frameworks). **foo.php** {% highlight php %} {% endhighlight %} -This is essentially the same as what most modern frameworks are doing, all be it a little more manual. You might -not need to do all of that every time, but mixing together too much presentation logic and database interaction can be a real problem if you ever want to [unit-test](/#unit-testing) your application. +This is essentially the same as what most modern frameworks are doing, all be it a little more manual. You might not +need to do all of that every time, but mixing together too much presentation logic and database interaction can be a +real problem if you ever want to [unit-test](/#unit-testing) your application. + +[PHPBridge] have a great resource called [Creating a Data Class] which covers a very similar topic, and is great for +developers just getting used to the concept of interacting with databases. -[PHPBridge] have a great resource called [Creating a Data Class] which covers a very similar topic, and is great -for developers just getting used to the concept of interacting with databases. [MVC]: http://code.tutsplus.com/tutorials/mvc-for-noobs--net-10488 [PHPBridge]: http://phpbridge.org/ diff --git a/_posts/07-05-01-Abstraction-Layers.md b/_posts/07-05-01-Abstraction-Layers.md new file mode 100644 index 0000000..718ee0a --- /dev/null +++ b/_posts/07-05-01-Abstraction-Layers.md @@ -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 diff --git a/_posts/08-01-01-Templating.md b/_posts/08-01-01-Templating.md index a8d3b27..b1af292 100644 --- a/_posts/08-01-01-Templating.md +++ b/_posts/08-01-01-Templating.md @@ -1,5 +1,5 @@ --- -title: Templating +title: Templating anchor: templating --- @@ -8,5 +8,4 @@ anchor: templating Templates provide a convenient way of separating your controller and domain logic from your presentation logic. Templates typically contain the HTML of your application, but may also be used for other formats, such as XML. Templates are often referred to as "views", which make up **part of** the second component of the -[model–view–controller](http://www.phptherightway.com/pages/Design-Patterns.html#model-view-controller) (MVC) -software architecture pattern. \ No newline at end of file +[model–view–controller](/pages/Design-Patterns.html#model-view-controller) (MVC) software architecture pattern. \ No newline at end of file diff --git a/_posts/08-02-01-Benefits.md b/_posts/08-02-01-Benefits.md index 8e21de7..0d379d4 100644 --- a/_posts/08-02-01-Benefits.md +++ b/_posts/08-02-01-Benefits.md @@ -1,6 +1,6 @@ --- isChild: true -anchor: templating_benefits +anchor: templating_benefits --- ## Benefits {#templating_benefits_title} diff --git a/_posts/08-03-01-Plain-PHP-Templates.md b/_posts/08-03-01-Plain-PHP-Templates.md index 57a6a53..7d08069 100644 --- a/_posts/08-03-01-Plain-PHP-Templates.md +++ b/_posts/08-03-01-Plain-PHP-Templates.md @@ -1,6 +1,6 @@ --- isChild: true -anchor: plain_php_templates +anchor: plain_php_templates --- ## Plain PHP Templates {#plain_php_templates_title} @@ -12,13 +12,12 @@ code editors already have PHP syntax highlighting and auto-completion built-in. very fast as no compiling stage is required. Every modern PHP framework employs some kind of template system, most of which use plain PHP by default. Outside of -frameworks, libraries like [Plates](http://platesphp.com/) or [Aura.View](https://github.com/auraphp/Aura.View) make -working with plain PHP templates easier by offering modern template functionality such as inheritance, layouts and -extensions. +frameworks, libraries like [Plates][plates] or [Aura.View][aura] make working with plain PHP templates easier by +offering modern template functionality such as inheritance, layouts and extensions. ### Simple example of a plain PHP template -Using the [Plates](http://platesphp.com/) library. +Using the [Plates][plates] library. {% highlight php %} @@ -33,7 +32,7 @@ Using the [Plates](http://platesphp.com/) library. ### Example of plain PHP templates using inheritance -Using the [Plates](http://platesphp.com/) library. +Using the [Plates][plates] library. {% highlight php %} @@ -59,4 +58,8 @@ Using the [Plates](http://platesphp.com/) library.Hello, =$this->escape($name)?>
-{% endhighlight %} \ No newline at end of file +{% endhighlight %} + + +[plates]: http://platesphp.com/ +[aura]: https://github.com/auraphp/Aura.View diff --git a/_posts/08-04-01-Compiled-Templates.md b/_posts/08-04-01-Compiled-Templates.md index e32d199..d8ed5dc 100644 --- a/_posts/08-04-01-Compiled-Templates.md +++ b/_posts/08-04-01-Compiled-Templates.md @@ -1,24 +1,22 @@ --- isChild: true -anchor: compiled_templates +anchor: compiled_templates --- -## Compiled Templates {#compiled_templates} +## Compiled Templates {#compiled_templates_title} -While PHP has evolved into a mature, object oriented language, it -[hasn't improved much](http://fabien.potencier.org/article/34/templating-engines-in-php) as a templating language. -Compiled templates, like [Twig](http://twig.sensiolabs.org/) or [Smarty](http://www.smarty.net/)*, fill this void by -offering a new syntax that has been geared specifically to templating. From automatic escaping, to inheritance and -simplified control structures, compiled templates are designed to be easier to write, cleaner to read and safer to use. -Compiled templates can even be shared across different languages, [Mustache](http://mustache.github.io/) being a good -example of this. Since these templates must be compiled there is a slight performance hit, however this is very minimal -when proper caching is used. +While PHP has evolved into a mature, object oriented language, it [hasn't improved much][article_templating_engines] as +a templating language. Compiled templates, like [Twig] or [Smarty]*, fill this void by offering a new syntax that has +been geared specifically to templating. From automatic escaping, to inheritance and simplified control structures, +compiled templates are designed to be easier to write, cleaner to read and safer to use. Compiled templates can even be +shared across different languages, [Mustache] being a good example of this. Since these templates must be compiled +there is a slight performance hit, however this is very minimal when proper caching is used. **While Smarty offers automatic escaping, this feature is NOT enabled by default.* ### Simple example of a compiled template -Using the [Twig](http://twig.sensiolabs.org/) library. +Using the [Twig] library. {% highlight html+jinja %} {% raw %} @@ -33,7 +31,7 @@ Using the [Twig](http://twig.sensiolabs.org/) library. ### Example of compiled templates using inheritance -Using the [Twig](http://twig.sensiolabs.org/) library. +Using the [Twig] library. {% highlight html+jinja %} {% raw %} @@ -67,3 +65,9 @@ Using the [Twig](http://twig.sensiolabs.org/) library. {% endblock %} {% endraw %} {% endhighlight %} + + +[article_templating_engines]: http://fabien.potencier.org/article/34/templating-engines-in-php +[Twig]: http://twig.sensiolabs.org/ +[Smarty]: http://www.smarty.net/ +[Mustache]: http://mustache.github.io/ diff --git a/_posts/08-05-01-Further-Reading.md b/_posts/08-05-01-Further-Reading.md index 02f3357..f042cab 100644 --- a/_posts/08-05-01-Further-Reading.md +++ b/_posts/08-05-01-Further-Reading.md @@ -1,28 +1,28 @@ --- isChild: true -anchor: templating_further_reading +anchor: templating_further_reading --- ## Further Reading {#templating_further_reading_title} ### Articles & Tutorials -- [Templating Engines in PHP](http://fabien.potencier.org/article/34/templating-engines-in-php) -- [An Introduction to Views & Templating in CodeIgniter](http://code.tutsplus.com/tutorials/an-introduction-to-views-templating-in-codeigniter--net-25648) -- [Getting Started With PHP Templating](http://www.smashingmagazine.com/2011/10/17/getting-started-with-php-templating/) -- [Roll Your Own Templating System in PHP](http://code.tutsplus.com/tutorials/roll-your-own-templating-system-in-php--net-16596) -- [Master Pages](https://laracasts.com/series/laravel-from-scratch/episodes/7) -- [Working With Templates in Symfony 2](http://code.tutsplus.com/tutorials/working-with-templates-in-symfony-2--cms-21172) +* [Templating Engines in PHP](http://fabien.potencier.org/article/34/templating-engines-in-php) +* [An Introduction to Views & Templating in CodeIgniter](http://code.tutsplus.com/tutorials/an-introduction-to-views-templating-in-codeigniter--net-25648) +* [Getting Started With PHP Templating](http://www.smashingmagazine.com/2011/10/17/getting-started-with-php-templating/) +* [Roll Your Own Templating System in PHP](http://code.tutsplus.com/tutorials/roll-your-own-templating-system-in-php--net-16596) +* [Master Pages](https://laracasts.com/series/laravel-from-scratch/episodes/7) +* [Working With Templates in Symfony 2](http://code.tutsplus.com/tutorials/working-with-templates-in-symfony-2--cms-21172) ### Libraries -- [Aura.View](https://github.com/auraphp/Aura.View) *(native)* -- [Blade](http://laravel.com/docs/templates) *(compiled, framework specific)* -- [Dwoo](http://dwoo.org/) *(compiled)* -- [Latte](https://github.com/nette/latte) *(compiled)* -- [Mustache](https://github.com/bobthecow/mustache.php) *(compiled)* -- [PHPTAL](http://phptal.org/) *(compiled)* -- [Plates](http://platesphp.com/) *(native)* -- [Smarty](http://www.smarty.net/) *(compiled)* -- [Twig](http://twig.sensiolabs.org/) *(compiled)* -- [Zend\View](http://framework.zend.com/manual/2.3/en/modules/zend.view.quick-start.html) *(native, framework specific)* +* [Aura.View](https://github.com/auraphp/Aura.View) *(native)* +* [Blade](http://laravel.com/docs/templates) *(compiled, framework specific)* +* [Dwoo](http://dwoo.org/) *(compiled)* +* [Latte](https://github.com/nette/latte) *(compiled)* +* [Mustache](https://github.com/bobthecow/mustache.php) *(compiled)* +* [PHPTAL](http://phptal.org/) *(compiled)* +* [Plates](http://platesphp.com/) *(native)* +* [Smarty](http://www.smarty.net/) *(compiled)* +* [Twig](http://twig.sensiolabs.org/) *(compiled)* +* [Zend\View](http://framework.zend.com/manual/2.3/en/modules/zend.view.quick-start.html) *(native, framework specific)* diff --git a/_posts/09-01-01-Errors-and-Exceptions.md b/_posts/09-01-01-Errors-and-Exceptions.md index 27e0b2e..379502d 100644 --- a/_posts/09-01-01-Errors-and-Exceptions.md +++ b/_posts/09-01-01-Errors-and-Exceptions.md @@ -1,5 +1,5 @@ --- -title: Errors and Exceptions +title: Errors and Exceptions anchor: errors_and_exceptions --- diff --git a/_posts/09-02-01-Errors.md b/_posts/09-02-01-Errors.md index 9b825b9..d435b42 100644 --- a/_posts/09-02-01-Errors.md +++ b/_posts/09-02-01-Errors.md @@ -1,6 +1,6 @@ --- isChild: true -anchor: errors +anchor: errors --- ## Errors {#errors_title} @@ -12,16 +12,16 @@ processing regardless of what happens, unless a fatal error occurs. For example: -{% highlight php %} +{% highlight console %} $ php -a php > echo $foo; Notice: Undefined variable: foo in php shell code on line 1 {% endhighlight %} -This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from "exception-heavy" -languages, because referencing a missing variable in Python for example will throw an exception: +This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from +"exception-heavy" languages, because referencing a missing variable in Python for example will throw an exception: -{% highlight python %} +{% highlight console %} $ python >>> print foo Traceback (most recent call last): @@ -31,102 +31,129 @@ NameError: name 'foo' is not defined The only real difference is that Python will freak out over any small thing, so that developers can be super sure any potential issue or edge-case is caught, whereas PHP will keep on processing unless something extreme happens, at which -point it will throw an error and report it. +point it will throw an error and report it. ### Error Severity -PHP has several levels of error severity. The three most common types of messages are errors, notices and warnings. -These have different levels of severity; `E_ERROR`, `E_NOTICE`, and `E_WARNING`. Errors are fatal run-time errors and -are usually caused by faults in your code and need to be fixed as they'll cause PHP to stop executing. Notices are advisory messages caused by code that may or may not cause problems during the execution of the script, execution is not halted. Warnings are non-fatal errors, execution of the script will not be halted. +PHP has several levels of error severity. The three most common types of messages are errors, notices and warnings. +These have different levels of severity; `E_ERROR`, `E_NOTICE`, and `E_WARNING`. Errors are fatal run-time errors and +are usually caused by faults in your code and need to be fixed as they'll cause PHP to stop executing. Notices are +advisory messages caused by code that may or may not cause problems during the execution of the script, execution is +not halted. Warnings are non-fatal errors, execution of the script will not be halted. Another type of error message reported at compile time are `E_STRICT` messages. These messages are used to suggest changes to your code to help ensure best interoperability and forward compatibility with upcoming versions of PHP. ### Changing PHP's Error Reporting Behaviour -Error Reporting can be changed by using PHP settings and/or PHP function calls. Using the built in PHP function -`error_reporting()` you can set the level of errors for the duration of the script execution by passing one of the -predefined error level constants, meaning if you only want to see Warnings and Errors - but not Notices - then -you can configure that: +Error Reporting can be changed by using PHP settings and/or PHP function calls. Using the built in PHP function +`error_reporting()` you can set the level of errors for the duration of the script execution by passing one of the +predefined error level constants, meaning if you only want to see Warnings and Errors - but not Notices - then you can +configure that: {% highlight php %} +upload->get_error()` to see what went wrong. The problem here is that you have to go -looking for a mistake and check the docs to see what the error method is for this class, instead of having it made extremely -obvious. +PHP itself is fairly lax with this, and a call to `file_get_contents()` will usually just get you a `FALSE` and a +warning. +Many older PHP frameworks like CodeIgniter will just return a false, log a message to their proprietary logs and maybe +let you use a method like `$this->upload->get_error()` to see what went wrong. The problem here is that you have to go +looking for a mistake and check the docs to see what the error method is for this class, instead of having it made +extremely obvious. -Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you -stop another developer from being able to dynamically handle that error. Exceptions should be thrown to make a developer -aware of an error; they then can choose how to handle this. E.g.: +Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you +stop another developer from being able to dynamically handle that error. Exceptions should be thrown to make a +developer aware of an error; they then can choose how to handle this. E.g.: {% highlight php %} lot of custom Exceptions, some of which could have been avoided using the SPL Exceptions -provided in the [SPL extension][splext]. +This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to the +creation of a lot of custom Exceptions, some of which could have been avoided using the SPL Exceptions +provided in the [SPL extension][splext]. -If for example you use the `__call()` Magic Method and an invalid method is requested then instead of throwing a standard -Exception which is vague, or creating a custom Exception just for that, you could just `throw new BadMethodCallException;`. +If for example you use the `__call()` Magic Method and an invalid method is requested then instead of throwing a +standard Exception which is vague, or creating a custom Exception just for that, you could just +`throw new BadMethodCallException;`. * [Read about Exceptions][exceptions] * [Read about SPL Exceptions][splexe] * [Nesting Exceptions In PHP][nesting-exceptions-in-php] * [Exception Best Practices in PHP 5.3][exception-best-practices53] -[exceptions]: http://php.net/manual/en/language.exceptions.php -[splexe]: http://php.net/manual/en/spl.exceptions.php + [splext]: /#standard_php_library -[exception-best-practices53]: http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3 +[exceptions]: http://php.net/language.exceptions +[splexe]: http://php.net/spl.exceptions [nesting-exceptions-in-php]: http://www.brandonsavage.net/exceptional-php-nesting-exceptions-in-php/ +[exception-best-practices53]: http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3 diff --git a/_posts/10-02-01-Web-Application-Security.md b/_posts/10-02-01-Web-Application-Security.md index da60b5f..61050dc 100644 --- a/_posts/10-02-01-Web-Application-Security.md +++ b/_posts/10-02-01-Web-Application-Security.md @@ -1,14 +1,17 @@ --- isChild: true -anchor: web_application_security +anchor: web_application_security --- ## Web Application Security {#web_application_security_title} -There are bad people ready and willing to exploit your web application. It is important that you - take necessary precautions to harden your web application's security. Luckily, the fine folks at [The Open Web Application Security Project][1] (OWASP) have compiled a comprehensive list of known security issues and methods to protect yourself against them. This is a must read for the security-conscious developer. +There are bad people ready and willing to exploit your web application. It is important that you take necessary +precautions to harden your web application's security. Luckily, the fine folks at +[The Open Web Application Security Project][1] (OWASP) have compiled a comprehensive list of known security issues and +methods to protect yourself against them. This is a must read for the security-conscious developer. * [Read the OWASP Security Guide][2] + [1]: https://www.owasp.org/ [2]: https://www.owasp.org/index.php/Guide_Table_of_Contents diff --git a/_posts/10-03-01-Password-Hashing.md b/_posts/10-03-01-Password-Hashing.md index d3e194d..ee70a65 100644 --- a/_posts/10-03-01-Password-Hashing.md +++ b/_posts/10-03-01-Password-Hashing.md @@ -1,23 +1,31 @@ --- isChild: true -anchor: password_hashing +anchor: password_hashing --- ## Password Hashing {#password_hashing_title} -Eventually everyone builds a PHP application that relies on user login. Usernames and passwords are stored in a database and later used to authenticate users upon login. +Eventually everyone builds a PHP application that relies on user login. Usernames and passwords are stored in a +database and later used to authenticate users upon login. -It is important that you properly [_hash_][3] passwords before storing them. Password hashing is an irreversible, one way function performed against the user's password. This produces a fixed-length string that cannot be feasibly reversed. This means you can compare a hash against another to determine if they both came from the same source string, but you cannot determine the original string. If passwords are not hashed and your database is accessed by an unauthorized third-party, all user accounts are now compromised. Some users may (unfortunately) use the same password for other services. Therefore, it is important to take security seriously. +It is important that you properly [_hash_][3] passwords before storing them. Password hashing is an irreversible, one +way function performed against the user's password. This produces a fixed-length string that cannot be feasibly +reversed. This means you can compare a hash against another to determine if they both came from the same source string, +but you cannot determine the original string. If passwords are not hashed and your database is accessed by an +unauthorized third-party, all user accounts are now compromised. Some users may (unfortunately) use the same password +for other services. Therefore, it is important to take security seriously. **Hashing passwords with `password_hash`** -In PHP 5.5 `password_hash` was introduced. At this time it is using BCrypt, the strongest algorithm currently supported by PHP. It will be updated in the future to support more algorithms as needed though. The `password_compat` library was created to provide forward compatibility for PHP >= 5.3.7. +In PHP 5.5 `password_hash()` was introduced. At this time it is using BCrypt, the strongest algorithm currently +supported by PHP. It will be updated in the future to support more algorithms as needed though. The `password_compat` +library was created to provide forward compatibility for PHP >= 5.3.7. -Below we hash a string, and then check the hash against a new string. Because our two source strings are different ('secret-password' vs. 'bad-password') this login will fail. +Below we hash a string, and then check the hash against a new string. Because our two source strings are different +('secret-password' vs. 'bad-password') this login will fail. {% highlight php %} = 5.3.7 && < 5.5] [2] +* [Learn about `password_hash()`] [1] +* [`password_compat` for PHP >= 5.3.7 && < 5.5] [2] * [Learn about hashing in regards to cryptography] [3] -* [PHP `password_hash` RFC] [4] +* [PHP `password_hash()` RFC] [4] -[1]: http://us2.php.net/manual/en/function.password-hash.php + +[1]: http://php.net/function.password-hash [2]: https://github.com/ircmaxell/password_compat [3]: http://en.wikipedia.org/wiki/Cryptographic_hash_function [4]: https://wiki.php.net/rfc/password_hash diff --git a/_posts/10-04-01-Data-Filtering.md b/_posts/10-04-01-Data-Filtering.md index b930eeb..dcba882 100644 --- a/_posts/10-04-01-Data-Filtering.md +++ b/_posts/10-04-01-Data-Filtering.md @@ -1,37 +1,34 @@ --- isChild: true -anchor: data_filtering +anchor: data_filtering --- ## Data Filtering {#data_filtering_title} -Never ever (ever) trust foreign input introduced to your PHP code. Always sanitize and validate -foreign input before using it in code. The `filter_var` and `filter_input` functions can sanitize text and validate text formats (e.g. +Never ever (ever) trust foreign input introduced to your PHP code. Always sanitize and validate foreign input before +using it in code. The `filter_var()` and `filter_input()` functions can sanitize text and validate text formats (e.g. email addresses). -Foreign input can be anything: `$_GET` and `$_POST` form input data, some values in the `$_SERVER` -superglobal, and the HTTP request body via `fopen('php://input', 'r')`. Remember, foreign input is not -limited to form data submitted by the user. Uploaded and downloaded files, session values, cookie data, -and data from third-party web services are foreign input, too. +Foreign input can be anything: `$_GET` and `$_POST` form input data, some values in the `$_SERVER` superglobal, and the +HTTP request body via `fopen('php://input', 'r')`. Remember, foreign input is not limited to form data submitted by the +user. Uploaded and downloaded files, session values, cookie data, and data from third-party web services are foreign +input, too. -While foreign data can be stored, combined, and accessed later, it is still foreign input. Every -time you process, output, concatenate, or include data in your code, ask yourself if -the data is filtered properly and can it be trusted. +While foreign data can be stored, combined, and accessed later, it is still foreign input. Every time you process, +output, concatenate, or include data in your code, ask yourself if the data is filtered properly and can it be trusted. -Data may be _filtered_ differently based on its purpose. For example, when unfiltered foreign input is passed -into HTML page output, it can execute HTML and JavaScript on your site! This is known as Cross-Site -Scripting (XSS) and can be a very dangerous attack. One way to avoid XSS is to sanitize all user-generated -data before outputting it to your page by removing HTML tags with the `strip_tags` function or escaping -characters with special meaning into their respective HTML entities with the `htmlentities` -or `htmlspecialchars` functions. +Data may be _filtered_ differently based on its purpose. For example, when unfiltered foreign input is passed into HTML +page output, it can execute HTML and JavaScript on your site! This is known as Cross-Site Scripting (XSS) and can be a +very dangerous attack. One way to avoid XSS is to sanitize all user-generated data before outputting it to your page by +removing HTML tags with the `strip_tags()` function or escaping characters with special meaning into their respective +HTML entities with the `htmlentities()` or `htmlspecialchars()` functions. -Another example is passing options to be executed on the command line. This can be extremely dangerous -(and is usually a bad idea), but you can use the built-in `escapeshellarg` function to sanitize the executed -command's arguments. +Another example is passing options to be executed on the command line. This can be extremely dangerous (and is usually +a bad idea), but you can use the built-in `escapeshellarg()` function to sanitize the executed command's arguments. One last example is accepting foreign input to determine a file to load from the filesystem. This can be exploited by -changing the filename to a file path. You need to remove "/", "../", [null bytes][6], or other characters from the file path so it can't -load hidden, non-public, or sensitive files. +changing the filename to a file path. You need to remove `"/"`, `"../"`, [null bytes][6], or other characters from the +file path so it can't load hidden, non-public, or sensitive files. * [Learn about data filtering][1] * [Learn about `filter_var`][4] @@ -42,28 +39,27 @@ load hidden, non-public, or sensitive files. Sanitization removes (or escapes) illegal or unsafe characters from foreign input. -For example, you should sanitize foreign input before including the input in HTML or inserting it -into a raw SQL query. When you use bound parameters with [PDO](#databases), it will -sanitize the input for you. +For example, you should sanitize foreign input before including the input in HTML or inserting it into a raw SQL query. +When you use bound parameters with [PDO](#databases), it will sanitize the input for you. -Sometimes it is required to allow some safe HTML tags in the input when including it in the HTML -page. This is very hard to do and many avoid it by using other more restricted formatting like -Markdown or BBCode, although whitelisting libraries like [HTML Purifier][html-purifier] exists for -this reason. +Sometimes it is required to allow some safe HTML tags in the input when including it in the HTML page. This is very +hard to do and many avoid it by using other more restricted formatting like Markdown or BBCode, although whitelisting +libraries like [HTML Purifier][html-purifier] exists for this reason. [See Sanitization Filters][2] ### Validation -Validation ensures that foreign input is what you expect. For example, you may want to validate an -email address, a phone number, or age when processing a registration submission. +Validation ensures that foreign input is what you expect. For example, you may want to validate an email address, a +phone number, or age when processing a registration submission. [See Validation Filters][3] -[1]: http://www.php.net/manual/en/book.filter.php -[2]: http://www.php.net/manual/en/filter.filters.sanitize.php -[3]: http://www.php.net/manual/en/filter.filters.validate.php -[4]: http://php.net/manual/en/function.filter-var.php -[5]: http://www.php.net/manual/en/function.filter-input.php -[6]: http://php.net/manual/en/security.filesystem.nullbytes.php + +[1]: http://php.net/book.filter +[2]: http://php.net/filter.filters.sanitize +[3]: http://php.net/filter.filters.validate +[4]: http://php.net/function.filter-var +[5]: http://php.net/function.filter-input +[6]: http://php.net/security.filesystem.nullbytes [html-purifier]: http://htmlpurifier.org/ diff --git a/_posts/10-05-01-Configuration-Files.md b/_posts/10-05-01-Configuration-Files.md index c5da2b3..e864bda 100644 --- a/_posts/10-05-01-Configuration-Files.md +++ b/_posts/10-05-01-Configuration-Files.md @@ -1,16 +1,16 @@ --- isChild: true -anchor: configuration_files +anchor: configuration_files --- ## Configuration Files {#configuration_files_title} -When creating configuration files for your applications, best practices recommend that one of the following methods -be followed: +When creating configuration files for your applications, best practices recommend that one of the following methods be +followed: -- It is recommended that you store your configuration information where it cannot be accessed directly and pulled in +- It is recommended that you store your configuration information where it cannot be accessed directly and pulled in via the file system. -- If you must store your configuration files in the document root, name the files with a `.php` extension. This -ensures that, even if the script is accessed directly, it will not be output as plain text. -- Information in configuration files should be protected accordingly, either through encryption or group/user file +- If you must store your configuration files in the document root, name the files with a `.php` extension. This ensures +that, even if the script is accessed directly, it will not be output as plain text. +- Information in configuration files should be protected accordingly, either through encryption or group/user file system permissions \ No newline at end of file diff --git a/_posts/10-06-01-Register-Globals.md b/_posts/10-06-01-Register-Globals.md index b2d1a62..79127d1 100644 --- a/_posts/10-06-01-Register-Globals.md +++ b/_posts/10-06-01-Register-Globals.md @@ -1,18 +1,18 @@ --- isChild: true -anchor: register_globals +anchor: register_globals --- ## Register Globals {#register_globals_title} -**NOTE:** As of PHP 5.4.0 the `register_globals` setting has been removed and can no -longer be used. This is only included as a warning for anyone in the process of upgrading a legacy application. +**NOTE:** As of PHP 5.4.0 the `register_globals` setting has been removed and can no longer be used. This is only +included as a warning for anyone in the process of upgrading a legacy application. -When enabled, the `register_globals` configuration setting that makes several types of variables (including ones from -`$_POST`, `$_GET` and `$_REQUEST`) available in the global scope of your application. This can easily lead to -security issues as your application cannot effectively tell where the data is coming from. +When enabled, the `register_globals` configuration setting that makes several types of variables (including ones from +`$_POST`, `$_GET` and `$_REQUEST`) available in the global scope of your application. This can easily lead to security +issues as your application cannot effectively tell where the data is coming from. -For example: `$_GET['foo']` would be available via `$foo`, which can override variables that have not been declared. +For example: `$_GET['foo']` would be available via `$foo`, which can override variables that have not been declared. If you are using PHP < 5.4.0 __make sure__ that `register_globals` is __off__. -* [Register_globals in the PHP manual](http://www.php.net/manual/en/security.globals.php) \ No newline at end of file +* [Register_globals in the PHP manual](http://php.net/security.globals) diff --git a/_posts/10-07-01-Error-Reporting.md b/_posts/10-07-01-Error-Reporting.md index b715ac1..46f595d 100644 --- a/_posts/10-07-01-Error-Reporting.md +++ b/_posts/10-07-01-Error-Reporting.md @@ -1,30 +1,33 @@ --- isChild: true -anchor: error_reporting +anchor: error_reporting --- ## Error Reporting {#error_reporting_title} -Error logging can be useful in finding the problem spots in your application, but it can also expose information about -the structure of your application to the outside world. To effectively protect your application from issues that could -be caused by the output of these messages, you need to configure your server differently in development versus +Error logging can be useful in finding the problem spots in your application, but it can also expose information about +the structure of your application to the outside world. To effectively protect your application from issues that could +be caused by the output of these messages, you need to configure your server differently in development versus production (live). ### Development To show every possible error during development, configure the following settings in your `php.ini`: - display_errors = On - display_startup_errors = On - error_reporting = -1 - log_errors = On +{% highlight ini %} +display_errors = On +display_startup_errors = On +error_reporting = -1 +log_errors = On +{% endhighlight %} -> Passing in the value `-1` will show every possible error, even when new levels and constants are added in future PHP versions. The `E_ALL` constant also behaves this way as of PHP 5.4. - [php.net](http://php.net/manual/function.error-reporting.php) +> Passing in the value `-1` will show every possible error, even when new levels and constants are added in future PHP +> versions. The `E_ALL` constant also behaves this way as of PHP 5.4. - +> [php.net](http://php.net/function.error-reporting) -The `E_STRICT` error level constant was introduced in 5.3.0 and is not -part of `E_ALL`, however it became part of `E_ALL` in 5.4.0. What does this mean? -In terms of reporting every possible error in version 5.3 it means you must -use either `-1` or `E_ALL | E_STRICT`. +The `E_STRICT` error level constant was introduced in 5.3.0 and is not part of `E_ALL`, however it became part of +`E_ALL` in 5.4.0. What does this mean? In terms of reporting every possible error in version 5.3 it means you must +use either `-1` or `E_ALL | E_STRICT`. **Reporting every possible error by PHP version** @@ -36,15 +39,17 @@ use either `-1` or `E_ALL | E_STRICT`. To hide errors on your production environment, configure your `php.ini` as: - display_errors = Off - display_startup_errors = Off - error_reporting = E_ALL - log_errors = On +{% highlight ini %} +display_errors = Off +display_startup_errors = Off +error_reporting = E_ALL +log_errors = On +{% endhighlight %} -With these settings in production, errors will still be logged to the error logs for the web server, but will not be +With these settings in production, errors will still be logged to the error logs for the web server, but will not be shown to the user. For more information on these settings, see the PHP manual: -* [error_reporting](http://php.net/manual/errorfunc.configuration.php#ini.error-reporting) -* [display_errors](http://php.net/manual/errorfunc.configuration.php#ini.display-errors) -* [display_startup_errors](http://php.net/manual/errorfunc.configuration.php#ini.display-startup-errors) -* [log_errors](http://php.net/manual/errorfunc.configuration.php#ini.log-errors) +* [error_reporting](http://php.net/errorfunc.configuration#ini.error-reporting) +* [display_errors](http://php.net/errorfunc.configuration#ini.display-errors) +* [display_startup_errors](http://php.net/errorfunc.configuration#ini.display-startup-errors) +* [log_errors](http://php.net/errorfunc.configuration#ini.log-errors) diff --git a/_posts/11-01-01-Testing.md b/_posts/11-01-01-Testing.md index f08fc4d..9fa8628 100644 --- a/_posts/11-01-01-Testing.md +++ b/_posts/11-01-01-Testing.md @@ -4,10 +4,10 @@ anchor: testing # Testing {#testing_title} -Writing automated tests for your PHP code is considered a best practice and can lead to well-built -applications. Automated tests are a great tool for making sure your application -does not break when you are making changes or adding new functionality and should not be ignored. +Writing automated tests for your PHP code is considered a best practice and can lead to well-built applications. +Automated tests are a great tool for making sure your application does not break when you are making changes or adding +new functionality and should not be ignored. -There are several different types of testing tools (or frameworks) available for PHP, which use -different approaches - all of which are trying to avoid manual testing and the need for large -Quality Assurance teams, just to make sure recent changes didn't break existing functionality. \ No newline at end of file +There are several different types of testing tools (or frameworks) available for PHP, which use different approaches - +all of which are trying to avoid manual testing and the need for large Quality Assurance teams, just to make sure +recent changes didn't break existing functionality. \ No newline at end of file diff --git a/_posts/11-02-01-Test-Driven-Development.md b/_posts/11-02-01-Test-Driven-Development.md index b3a7e46..db7188c 100644 --- a/_posts/11-02-01-Test-Driven-Development.md +++ b/_posts/11-02-01-Test-Driven-Development.md @@ -1,35 +1,39 @@ --- isChild: true -anchor: test_driven_development +anchor: test_driven_development --- ## Test Driven Development {#test_driven_development_title} From [Wikipedia](http://en.wikipedia.org/wiki/Test-driven_development): -> Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finally refactors the new code to acceptable standards. Kent Beck, who is credited with having developed or 'rediscovered' the technique, stated in 2003 that TDD encourages simple designs and inspires confidence +> Test-driven development (TDD) is a software development process that relies on the repetition of a very short +> development cycle: first the developer writes a failing automated test case that defines a desired improvement or new +> function, then produces code to pass that test and finally refactors the new code to acceptable standards. Kent Beck, +> who is credited with having developed or 'rediscovered' the technique, stated in 2003 that TDD encourages simple +> designs and inspires confidence. -There are several different types of testing that you can do for your application +There are several different types of testing that you can do for your application: ### Unit Testing -Unit Testing is a programming approach to ensure functions, classes and methods are working as -expected, from the point you build them all the way through the development cycle. By checking -values going in and out of various functions and methods, you can make sure the internal logic is -working correctly. By using Dependency Injection and building "mock" classes and stubs you can verify that dependencies are correctly used for even better test coverage. +Unit Testing is a programming approach to ensure functions, classes and methods are working as expected, from the point +you build them all the way through the development cycle. By checking values going in and out of various functions and +methods, you can make sure the internal logic is working correctly. By using Dependency Injection and building "mock" +classes and stubs you can verify that dependencies are correctly used for even better test coverage. -When you create a class or function you should create a unit test for each behavior it must have. At a very basic level you should -make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments. -This will help ensure that when you make changes to this class or function later on in the development -cycle that the old functionality continues to work as expected. The only alternative to this would be -var_dump() in a test.php, which is no way to build an application - large or small. +When you create a class or function you should create a unit test for each behavior it must have. At a very basic level +you should make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments. This +will help ensure that when you make changes to this class or function later on in the development cycle that the old +functionality continues to work as expected. The only alternative to this would be `var_dump()` in a test.php, which is +no way to build an application - large or small. -The other use for unit tests is contributing to open source. If you can write a test that shows broken -functionality (i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If -you run a project which accepts pull requests then you should suggest this as a requirement. +The other use for unit tests is contributing to open source. If you can write a test that shows broken functionality +(i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If you run a project +which accepts pull requests then you should suggest this as a requirement. -[PHPUnit](http://phpunit.de) is the de-facto testing framework for writing unit tests for PHP -applications, but there are several alternatives +[PHPUnit](http://phpunit.de) is the de-facto testing framework for writing unit tests for PHP applications, but there +are several alternatives * [atoum](https://github.com/atoum/atoum) * [Enhance PHP](https://github.com/Enhance-PHP/Enhance-PHP) @@ -41,17 +45,21 @@ applications, but there are several alternatives From [Wikipedia](http://en.wikipedia.org/wiki/Integration_testing): -> Integration testing (sometimes called Integration and Testing, abbreviated "I&T") is the phase in software testing in which individual software modules are combined and tested as a group. It occurs after unit testing and before validation testing. Integration testing takes as its input modules that have been unit tested, groups them in larger aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the integrated system ready for system testing. +> Integration testing (sometimes called Integration and Testing, abbreviated "I&T") is the phase in software testing in +> which individual software modules are combined and tested as a group. It occurs after unit testing and before +> validation testing. Integration testing takes as its input modules that have been unit tested, groups them in larger +> aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the +> integrated system ready for system testing. -Many of the same tools that can be used for unit testing can be used for integration testing as many -of the same principles are used. +Many of the same tools that can be used for unit testing can be used for integration testing as many of the same +principles are used. ### Functional Testing -Sometimes also known as acceptance testing, functional testing consists of using tools to create automated -tests that actually use your application instead of just verifying that individual units of code are behaving -correctly and that individual units can speak to each other correctly. These tools typically work using real -data and simulating actual users of the application. +Sometimes also known as acceptance testing, functional testing consists of using tools to create automated tests that +actually use your application instead of just verifying that individual units of code are behaving correctly and that +individual units can speak to each other correctly. These tools typically work using real data and simulating actual +users of the application. #### Functional Testing Tools diff --git a/_posts/11-03-01-Behavior-Driven-Development.md b/_posts/11-03-01-Behavior-Driven-Development.md index 5e1ce10..4585162 100644 --- a/_posts/11-03-01-Behavior-Driven-Development.md +++ b/_posts/11-03-01-Behavior-Driven-Development.md @@ -1,23 +1,31 @@ --- isChild: true -anchor: behavior_driven_development +anchor: behavior_driven_development --- ## Behavior Driven Development {#behavior_driven_development_title} -There are two different types of Behavior-Driven Development (BDD): SpecBDD and StoryBDD. SpecBDD focuses on technical behavior of code, while StoryBDD focuses on business or feature behaviors or interactions. PHP has frameworks for both types of BDD. +There are two different types of Behavior-Driven Development (BDD): SpecBDD and StoryBDD. SpecBDD focuses on technical +behavior of code, while StoryBDD focuses on business or feature behaviors or interactions. PHP has frameworks for both +types of BDD. -With StoryBDD, you write human-readable stories that describe the behavior of your application. These stories -can then be run as actual tests against your application. The framework used in PHP applications for StoryBDD -is Behat, which is inspired by Ruby's [Cucumber](http://cukes.info/) project and implements the Gherkin DSL -for describing feature behavior. +With StoryBDD, you write human-readable stories that describe the behavior of your application. These stories can then +be run as actual tests against your application. The framework used in PHP applications for StoryBDD is [Behat], which +is inspired by Ruby's [Cucumber] project and implements the Gherkin DSL for describing feature behavior. -With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing -a function or method, you are describing how that function or method should behave. PHP offers the PHPSpec framework for this purpose. This framework is inspired -by the [RSpec project](http://rspec.info/) for Ruby. +With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing a function +or method, you are describing how that function or method should behave. PHP offers the [PHPSpec] framework for this +purpose. This framework is inspired by the [RSpec project][Rspec] for Ruby. ### BDD Links -* [Behat](http://behat.org/), the StoryBDD framework for PHP, inspired by Ruby's [Cucumber](http://cukes.info/) project; -* [PHPSpec](http://www.phpspec.net/), the SpecBDD framework for PHP, inspired by Ruby's [RSpec](http://rspec.info/) project; -* [Codeception](http://codeception.com) is a full-stack testing framework that uses BDD principles. +* [Behat], the StoryBDD framework for PHP, inspired by Ruby's [Cucumber] project; +* [PHPSpec], the SpecBDD framework for PHP, inspired by Ruby's [RSpec] project; +* [Codeception] is a full-stack testing framework that uses BDD principles. + + +[Behat]: http://behat.org/ +[Cucumber]: http://cukes.info/ +[PHPSpec]: http://www.phpspec.net/ +[RSpec]: http://rspec.info/ +[Codeception]: http://codeception.com/ diff --git a/_posts/11-04-01-Complementary-Testing-Tools.md b/_posts/11-04-01-Complementary-Testing-Tools.md index 181824d..8bd3084 100644 --- a/_posts/11-04-01-Complementary-Testing-Tools.md +++ b/_posts/11-04-01-Complementary-Testing-Tools.md @@ -1,14 +1,24 @@ --- isChild: true -anchor: complementary_testing_tools +anchor: complementary_testing_tools --- ## Complementary Testing Tools {#complementary_testing_tools_title} -Besides individual testing and behavior driven frameworks, there are also a number of generic frameworks and helper libraries useful for any preferred approach taken. +Besides individual testing and behavior driven frameworks, there are also a number of generic frameworks and helper +libraries useful for any preferred approach taken. ### Tool Links -* [Selenium](http://seleniumhq.org/) is a browser automation tool which can be [integrated with PHPUnit](http://phpunit.de/manual/current/en/selenium.html) -* [Mockery](https://github.com/padraic/mockery) is a Mock Object Framework which can be integrated with [PHPUnit](http://phpunit.de/) or [PHPSpec](http://www.phpspec.net/) -* [Prophecy](https://github.com/phpspec/prophecy) is a highly opinionated yet very powerful and flexible PHP object mocking framework. It's integrated with [PHPSpec](http://www.phpspec.net/) and can be used with [PHPUnit](http://phpunit.de/). +* [Selenium] is a browser automation tool which can be [integrated with PHPUnit] +* [Mockery] is a Mock Object Framework which can be integrated with [PHPUnit] or [PHPSpec] +* [Prophecy] is a highly opinionated yet very powerful and flexible PHP object mocking framework. It's integrated with +[PHPSpec] and can be used with [PHPUnit]. + + +[Selenium]: http://seleniumhq.org/ +[integrated with PHPUnit]: http://phpunit.de/manual/current/en/selenium.html +[Mockery]: https://github.com/padraic/mockery +[PHPUnit]: http://phpunit.de/ +[PHPSpec]: http://www.phpspec.net/ +[Prophecy]: https://github.com/phpspec/prophecy diff --git a/_posts/12-02-01-Platform-as-a-Service.md b/_posts/12-02-01-Platform-as-a-Service.md index 4df180b..22ee244 100644 --- a/_posts/12-02-01-Platform-as-a-Service.md +++ b/_posts/12-02-01-Platform-as-a-Service.md @@ -1,13 +1,13 @@ --- -title: Platform as a Service (PaaS) +title: Platform as a Service (PaaS) isChild: true -anchor: platform_as_a_service +anchor: platform_as_a_service --- -## Platform as a Service (PaaS) {#platform_as_a_service_title} +## Platform as a Service (PaaS) {#platform_as_a_service_title} -PaaS provides the system and network architecture necessary to run PHP applications on the web. This means little to no -configuration for launching PHP applications or PHP frameworks. +PaaS provides the system and network architecture necessary to run PHP applications on the web. This means little to no +configuration for launching PHP applications or PHP frameworks. -Recently PaaS has become a popular method for deploying, hosting, and scaling PHP applications of all sizes. You can -find a list of [PHP PaaS "Platform as a Service" providers](#php-paas-providers) in our [resources section](#resources). \ No newline at end of file +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). \ No newline at end of file diff --git a/_posts/12-03-01-Virtual-or-Dedicated-Servers.md b/_posts/12-03-01-Virtual-or-Dedicated-Servers.md index 465b319..322bdb6 100644 --- a/_posts/12-03-01-Virtual-or-Dedicated-Servers.md +++ b/_posts/12-03-01-Virtual-or-Dedicated-Servers.md @@ -1,29 +1,53 @@ --- isChild: true -anchor: virtual_or_dedicated_servers +anchor: virtual_or_dedicated_servers --- ## Virtual or Dedicated Servers {#virtual_or_dedicated_servers_title} -If you are comfortable with systems administration, or are interested in learning it, virtual or dedicated servers give you complete control of your application's production environment. +If you are comfortable with systems administration, or are interested in learning it, virtual or dedicated servers give +you complete control of your application's production environment. ### nginx and PHP-FPM -PHP, via PHP's built-in FastCGI Process Manager (FPM), pairs really nicely with [nginx](http://nginx.org), which is a lightweight, high-performance web server. It uses less memory than Apache and can better handle more concurrent requests. This is especially important on virtual servers that don't have much memory to spare. +PHP, via PHP's built-in FastCGI Process Manager (FPM), pairs really nicely with [nginx], which is a lightweight, +high-performance web server. It uses less memory than Apache and can better handle more concurrent requests. This is +especially important on virtual servers that don't have much memory to spare. -* [Read more on nginx](http://nginx.org) -* [Read more on PHP-FPM](http://php.net/manual/en/install.fpm.php) -* [Read more on setting up nginx and PHP-FPM securely](https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/) +* [Read more on nginx][nginx] +* [Read more on PHP-FPM][phpfpm] +* [Read more on setting up nginx and PHP-FPM securely][secure-nginx-phpfpm] ### Apache and PHP -PHP and Apache have a long history together. Apache is wildly configurable and has many available [modules](http://httpd.apache.org/docs/2.4/mod/) to extend functionality. It is a popular choice for shared servers and an easy setup for PHP frameworks and open source apps like WordPress. Unfortunately, Apache uses more resources than nginx by default and cannot handle as many visitors at the same time. +PHP and Apache have a long history together. Apache is wildly configurable and has many available +[modules][apache-modules] to extend functionality. It is a popular choice for shared servers and an easy setup for PHP +frameworks and open source apps like WordPress. Unfortunately, Apache uses more resources than nginx by default and +cannot handle as many visitors at the same time. -Apache has several possible configurations for running PHP. The most common and easiest to setup is the [prefork MPM](http://httpd.apache.org/docs/2.4/mod/prefork.html) with mod_php5. While it isn't the most memory efficient, it is the simplest to get working and to use. This is probably the best choice if you don't want to dig too deeply into the server administration aspects. Note that if you use mod_php5 you MUST use the prefork MPM. +Apache has several possible configurations for running PHP. The most common and easiest to setup is the [prefork MPM] +with mod_php5. While it isn't the most memory efficient, it is the simplest to get working and to use. This is probably +the best choice if you don't want to dig too deeply into the server administration aspects. Note that if you use +mod_php5 you MUST use the prefork MPM. -Alternatively, if you want to squeeze more performance and stability out of Apache then you can take advantage of the same FPM system as nginx and run the [worker MPM](http://httpd.apache.org/docs/2.4/mod/worker.html) or [event MPM](http://httpd.apache.org/docs/2.4/mod/event.html) with mod_fastcgi or mod_fcgid. This configuration will be significantly more memory efficient and much faster but it is more work to set up. +Alternatively, if you want to squeeze more performance and stability out of Apache then you can take advantage of the +same FPM system as nginx and run the [worker MPM] or [event MPM] with mod_fastcgi or mod_fcgid. This configuration will +be significantly more memory efficient and much faster but it is more work to set up. -* [Read more on Apache](http://httpd.apache.org/) -* [Read more on Multi-Processing Modules](http://httpd.apache.org/docs/2.4/mod/mpm_common.html) -* [Read more on mod_fastcgi](http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html) -* [Read more on mod_fcgid](http://httpd.apache.org/mod_fcgid/) +* [Read more on Apache][apache] +* [Read more on Multi-Processing Modules][apache-MPM] +* [Read more on mod_fastcgi][mod_fastcgi] +* [Read more on mod_fcgid][mod_fcgid] + + +[nginx]: http://nginx.org/ +[phpfpm]: http://php.net/install.fpm +[secure-nginx-phpfpm]: https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/ +[apache-modules]: http://httpd.apache.org/docs/2.4/mod/ +[prefork MPM]: http://httpd.apache.org/docs/2.4/mod/prefork.html +[worker MPM]: http://httpd.apache.org/docs/2.4/mod/worker.html +[event MPM]: http://httpd.apache.org/docs/2.4/mod/event.html +[apache]: http://httpd.apache.org/ +[apache-MPM]: http://httpd.apache.org/docs/2.4/mod/mpm_common.html +[mod_fastcgi]: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html +[mod_fcgid]: http://httpd.apache.org/mod_fcgid/ \ No newline at end of file diff --git a/_posts/12-04-01-Shared-Servers.md b/_posts/12-04-01-Shared-Servers.md index d21afbe..33682ee 100644 --- a/_posts/12-04-01-Shared-Servers.md +++ b/_posts/12-04-01-Shared-Servers.md @@ -1,8 +1,12 @@ --- isChild: true -anchor: shared_servers +anchor: shared_servers --- ## Shared Servers {#shared_servers_title} -PHP has shared servers to thank for its popularity. It is hard to find a host without PHP installed, but be sure it's the latest version. Shared servers allow you and other developers to deploy websites to a single machine. The upside to this is that it has become a cheap commodity. The downside is that you never know what kind of a ruckus your neighboring tenants are going to create; loading down the server or opening up security holes are the main concerns. If your project's budget can afford to avoid shared servers you should. +PHP has shared servers to thank for its popularity. It is hard to find a host without PHP installed, but be sure it's +the latest version. Shared servers allow you and other developers to deploy websites to a single machine. The upside to +this is that it has become a cheap commodity. The downside is that you never know what kind of a ruckus your +neighboring tenants are going to create; loading down the server or opening up security holes are the main concerns. If +your project's budget can afford to avoid shared servers you should. diff --git a/_posts/12-05-01-Building-your-Application.md b/_posts/12-05-01-Building-your-Application.md index 847fa3e..50dfbde 100644 --- a/_posts/12-05-01-Building-your-Application.md +++ b/_posts/12-05-01-Building-your-Application.md @@ -1,15 +1,14 @@ --- isChild: true -anchor: building_and_deploying_your_application +anchor: building_and_deploying_your_application --- ## Building and Deploying your Application {#building_and_deploying_your_application_title} -If you find yourself doing manual database schema changes or running your tests manually before updating your files -(manually), think twice! With every additional manual task needed to deploy a new version of your app, the chances for -potentially fatal mistakes increase. Whether you're dealing with a simple update, a comprehensive build process or -even a continuous integration strategy, [build automation](http://en.wikipedia.org/wiki/Build_automation) is your -friend. +If you find yourself doing manual database schema changes or running your tests manually before updating your files +(manually), think twice! With every additional manual task needed to deploy a new version of your app, the chances for +potentially fatal mistakes increase. Whether you're dealing with a simple update, a comprehensive build process or even +a continuous integration strategy, [build automation][buildautomation] is your friend. Among the tasks you might want to automate are: @@ -23,53 +22,70 @@ Among the tasks you might want to automate are: ### Build Automation Tools -Build tools can be described as a collection of scripts that handle common tasks of software deployment. The build -tool is not a part of your software, it acts on your software from 'outside'. +Build tools can be described as a collection of scripts that handle common tasks of software deployment. The build tool +is not a part of your software, it acts on your software from 'outside'. -There are many open source tools available to help you with build automation, some are written in PHP others aren't. +There are many open source tools available to help you with build automation, some are written in PHP others aren't. This shouldn't hold you back from using them, if they're better suited for the specific job. Here are a few examples: -[Phing](http://www.phing.info/) is the easiest way to get started with automated deployment in the PHP world. With -Phing you can control your packaging, deployment or testing process from within a simple XML build file. Phing (which -is based on [Apache Ant](http://ant.apache.org/)) provides a rich set of tasks usually needed to install or update a -web app and can be extended with additional custom tasks, written in PHP. +[Phing] is the easiest way to get started with automated deployment in the PHP world. With Phing you can control your +packaging, deployment or testing process from within a simple XML build file. Phing (which is based on [Apache Ant]) +provides a rich set of tasks usually needed to install or update a web app and can be extended with additional custom +tasks, written in PHP. -[Capistrano](https://github.com/capistrano/capistrano/wiki) is a system for *intermediate-to-advanced programmers* to -execute commands in a structured, repeatable way on one or more remote machines. It is pre-configured for deploying -Ruby on Rails applications, however people are **successfully deploying PHP systems** with it. Successful use of -Capistrano depends on a working knowledge of Ruby and Rake. +[Capistrano] is a system for *intermediate-to-advanced programmers* to execute commands in a structured, repeatable way +on one or more remote machines. It is pre-configured for deploying Ruby on Rails applications, however people are ** +successfully deploying PHP systems** with it. Successful use of Capistrano depends on a working knowledge of Ruby and +Rake. -Dave Gardner's blog post [PHP Deployment with Capistrano](http://www.davegardner.me.uk/blog/2012/02/13/php-deployment-with-capistrano/) -is a good starting point for PHP developers interested in Capistrano. +Dave Gardner's blog post [PHP Deployment with Capistrano][phpdeploy_capistrano] is a good starting point for PHP +developers interested in Capistrano. -[Chef](http://www.opscode.com/chef/) is more than a deployment framework, it is a very powerful Ruby based system -integration framework that doesn't just deploy your app but can build your whole server environment or virtual boxes. +[Chef] is more than a deployment framework, it is a very powerful Ruby based system integration framework that doesn't +just deploy your app but can build your whole server environment or virtual boxes. -Chef resources for PHP developers: +#### Chef resources for PHP developers: -* [Three part blog series about deploying a LAMP application with Chef, Vagrant, and EC2](http://www.jasongrimes.org/2012/06/managing-lamp-environments-with-chef-vagrant-and-ec2-1-of-3/) -* [Chef Cookbook which installs and configures PHP 5.3 and the PEAR package management system](https://github.com/opscode-cookbooks/php) -* [Chef video tutorial series by Opscode, the makers of chef](https://www.youtube.com/playlist?list=PLrmstJpucjzWKt1eWLv88ZFY4R1jW8amR) -Further reading: +* [Three part blog series about deploying a LAMP application with Chef, Vagrant, and EC2][chef_vagrant_and_ec2] +* [Chef Cookbook which installs and configures PHP 5.3 and the PEAR package management system][Chef_cookbook] +* [Chef video tutorial series][Chef_tutorial] by Opscode, the makers of chef -* [Automate your project with Apache Ant](http://net.tutsplus.com/tutorials/other/automate-your-projects-with-apache-ant/) +#### Further reading: + +* [Automate your project with Apache Ant][apache_ant_tutorial] ### Continuous Integration -> Continuous Integration is a software development practice where members of a team integrate their work frequently, -> usually each person integrates at least daily — leading to multiple integrations per day. Many teams find that this -> approach leads to significantly reduced integration problems and allows a team to develop cohesive software more +> Continuous Integration is a software development practice where members of a team integrate their work frequently, +> usually each person integrates at least daily — leading to multiple integrations per day. Many teams find that this +> approach leads to significantly reduced integration problems and allows a team to develop cohesive software more > rapidly. *-- Martin Fowler* -There are different ways to implement continuous integration for PHP. Recently [Travis CI](https://travis-ci.org/) has -done a great job of making continuous integration a reality even for small projects. Travis CI is a hosted continuous -integration service for the open source community. It is integrated with GitHub and offers first class support for many -languages including PHP. +There are different ways to implement continuous integration for PHP. Recently [Travis CI] has done a great job of +making continuous integration a reality even for small projects. Travis CI is a hosted continuous integration service +for the open source community. It is integrated with GitHub and offers first class support for many languages including +PHP. -Further reading: +#### Further reading: -* [Continuous Integration with Jenkins](http://jenkins-ci.org/) -* [Continuous Integration with PHPCI](http://www.phptesting.org/) -* [Continuous Integration with Teamcity](http://www.jetbrains.com/teamcity/) +* [Continuous Integration with Jenkins][Jenkins] +* [Continuous Integration with PHPCI][PHPCI] +* [Continuous Integration with Teamcity][Teamcity] + + +[buildautomation]: http://en.wikipedia.org/wiki/Build_automation +[Phing]: http://www.phing.info/ +[Apache Ant]: http://ant.apache.org/ +[Capistrano]: https://github.com/capistrano/capistrano/wiki +[phpdeploy_capistrano]: http://www.davegardner.me.uk/blog/2012/02/13/php-deployment-with-capistrano/ +[Chef]: http://www.opscode.com/chef/ +[chef_vagrant_and_ec2]: http://www.jasongrimes.org/2012/06/managing-lamp-environments-with-chef-vagrant-and-ec2-1-of-3/ +[Chef_cookbook]: https://github.com/opscode-cookbooks/php +[Chef_tutorial]: https://www.youtube.com/playlist?list=PLrmstJpucjzWKt1eWLv88ZFY4R1jW8amR +[apache_ant_tutorial]: http://net.tutsplus.com/tutorials/other/automate-your-projects-with-apache-ant/ +[Travis CI]: https://travis-ci.org/ +[Jenkins]: http://jenkins-ci.org/ +[PHPCI]: http://www.phptesting.org/ +[Teamcity]: http://www.jetbrains.com/teamcity/ \ No newline at end of file diff --git a/_posts/13-01-01-Virtualization.md b/_posts/13-01-01-Virtualization.md index 9364895..1c9706f 100644 --- a/_posts/13-01-01-Virtualization.md +++ b/_posts/13-01-01-Virtualization.md @@ -4,11 +4,11 @@ anchor: virtualization # Virtualization -Running your application on different environments in development and production can lead to strange bugs -popping up when you go live. It's also tricky to keep different development environments up to date with the same -version for all libraries used when working with a team of developers. +Running your application on different environments in development and production can lead to strange bugs popping up +when you go live. It's also tricky to keep different development environments up to date with the same version for all +libraries used when working with a team of developers. -If you are developing on Windows and deploying to Linux (or anything non-Windows) or are developing in a team, you -should consider using a virtual machine. -This sounds tricky, but besides the widely known virtualization environments like VMware or VirtualBox, there are -additional tools that may help you setting up a virtual environment in a few easy steps. +If you are developing on Windows and deploying to Linux (or anything non-Windows) or are developing in a team, you +should consider using a virtual machine. This sounds tricky, but besides the widely known virtualization environments +like VMware or VirtualBox, there are additional tools that may help you setting up a virtual environment in a few easy +steps. diff --git a/_posts/13-02-01-Vagrant.md b/_posts/13-02-01-Vagrant.md index dd68afc..9210827 100644 --- a/_posts/13-02-01-Vagrant.md +++ b/_posts/13-02-01-Vagrant.md @@ -1,36 +1,37 @@ --- isChild: true -anchor: vagrant +anchor: vagrant --- ## Vagrant {#vagrant_title} -[Vagrant][vagrant] helps you building your virtual boxes on top of the known virtual environments and will configure -these environments based on a single configuration file. -These boxes can be set up manually, or you can use "provisioning" -software such as [Puppet][puppet] or [Chef][chef] to do this for you. Provisioning the base box is a great way to -ensure that multiple boxes are set up in an identical fashion and removes the need for you to maintain complicated -"set up" command lists. You can also "destroy" your base box and recreate it without many manual steps, making it -easy to create a "fresh" installation. +[Vagrant] helps you building your virtual boxes on top of the known virtual environments and will configure these +environments based on a single configuration file. These boxes can be set up manually, or you can use "provisioning" +software such as [Puppet] or [Chef] to do this for you. Provisioning the base box is a great way to ensure that +multiple boxes are set up in an identical fashion and removes the need for you to maintain complicated "set up" +command lists. You can also "destroy" your base box and recreate it without many manual steps, making it easy to create +a "fresh" installation. -Vagrant creates folders for sharing your code between your host and your virtual machine, which means that you can +Vagrant creates folders for sharing your code between your host and your virtual machine, which means that you can create and edit your files on your host machine and then run the code inside your virtual machine. ### A little help If you need a little help to start using Vagrant there are some services that might be useful: -- [Rove][rove]: service that allows you to pre-generate typical Vagrant builds, PHP among the options. The - provisioning is made with Chef. -- [Puphpet][puphpet]: simple GUI to set up virtual machines for PHP development. **Heavily focused in PHP**. Besides - local VMs, it can be used to deploy to cloud services as well. The provisioning is made with Puppet. -- [Protobox][protobox]: is a layer on top of vagrant and a web GUI to setup virtual machines for web development. A single YAML document controls everything that is installed on the virtual machine. -- [Phansible][phansible]: provides an easy to use interface that helps you generate Ansible Playbooks for PHP based projects. +- [Rove]: service that allows you to pre-generate typical Vagrant builds, PHP among the options. The provisioning is +made with Chef. +- [Puphpet]: simple GUI to set up virtual machines for PHP development. **Heavily focused in PHP**. Besides local VMs, +it can be used to deploy to cloud services as well. The provisioning is made with Puppet. +- [ Protobox]: is a layer on top of vagrant and a web GUI to setup virtual machines for web development. A single YAML +document controls everything that is installed on the virtual machine. +- [Phansible]: provides an easy to use interface that helps you generate Ansible Playbooks for PHP based projects. -[vagrant]: http://vagrantup.com/ -[puppet]: http://www.puppetlabs.com/ -[chef]: http://www.opscode.com/ -[rove]: http://rove.io/ -[puphpet]: https://puphpet.com/ -[protobox]: http://getprotobox.com/ -[phansible]: http://phansible.com/ + +[Vagrant]: http://vagrantup.com/ +[Puppet]: http://www.puppetlabs.com/ +[Chef]: http://www.opscode.com/ +[Rove]: http://rove.io/ +[Puphpet]: https://puphpet.com/ +[Protobox]: http://getprotobox.com/ +[Phansible]: http://phansible.com/ diff --git a/_posts/13-03-01-Docker.md b/_posts/13-03-01-Docker.md index 36fa829..3a98313 100644 --- a/_posts/13-03-01-Docker.md +++ b/_posts/13-03-01-Docker.md @@ -1,42 +1,45 @@ --- isChild: true -anchor: docker +anchor: docker --- ## Docker {#docker_title} -Beside using Vagrant, another easy way to get a virtual development or production environment up and running is [Docker][docker]. +Beside using Vagrant, another easy way to get a virtual development or production environment up and running is [Docker]. Docker helps you to provide Linux containers for all kind of applications. There are many helpful docker images which could provide you with other great services without the need to install -these services on your local machine, e.g. MySQL or PostgreSQL and a lot more. -Have a look at the [Docker Hub Registry][docker-hub] to search a list of available pre-built containers, -which you can then run and use in very few steps. +these services on your local machine, e.g. MySQL or PostgreSQL and a lot more. Have a look at the [Docker Hub Registry] +[docker-hub] to search a list of available pre-built containers, which you can then run and use in very few steps. ### Example: Runnning your PHP Applications in Docker -After you [installed docker][docker-install] on your machine, you can start an Apache with PHP support in one step. + +After you [installed docker][docker-install] on your machine, you can start an Apache with PHP support in one step. The following command will download a fully functional Apache installation with the latest PHP version and provide the directory `/path/to/your/php/files` at `http://localhost:8080`: -{% highlight bash %} -docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache +{% highlight console %} +docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache {% endhighlight %} -After running `docker run` your container is initialized and running. +After running `docker run` your container is initialized and running. If you would like to stop or start your container again, you can use the provided name attribute and simply run -`docker stop my-php-webserver` and `docker start my-php-webserver` without providing the above mentioned parameters again. - -### Learn more about Docker -The commands mentioned above only show a quick way to run an Apache web server with PHP support but there are a lot more -things that you can do with Docker. -One of the most important things for PHP developers will be linking your web server to a database instance, for example. -How this could be done is well described within the [Docker User Guide][docker-doc]. +`docker stop my-php-webserver` and `docker start my-php-webserver` without providing the above mentioned parameters +again. -* [Docker Website][docker] +### Learn more about Docker + +The commands mentioned above only show a quick way to run an Apache web server with PHP support but there are a lot +more things that you can do with Docker. One of the most important things for PHP developers will be linking your +web server to a database instance, for example. How this could be done is well described within the [Docker User Guide] +[docker-doc]. + +* [Docker Website][Docker] * [Docker Installation][docker-install] * [Docker Images at the Docker Hub Registry][docker-hub] * [Docker User Guide][docker-doc] -[docker]: http://docker.com/ + +[Docker]: http://docker.com/ [docker-hub]: https://registry.hub.docker.com/ [docker-install]: https://docs.docker.com/installation/ [docker-doc]: https://docs.docker.com/userguide/ diff --git a/_posts/14-01-01-Caching.md b/_posts/14-01-01-Caching.md index ce3c77e..0c5dd70 100644 --- a/_posts/14-01-01-Caching.md +++ b/_posts/14-01-01-Caching.md @@ -5,4 +5,4 @@ anchor: caching # Caching {#caching_title} PHP is pretty quick by itself, but bottlenecks can arise when you make remote connections, load files, etc. -Thankfully, there are various tools available to speed up certain parts of your application, or reduce the number of times these various time-consuming tasks need to run. \ No newline at end of file +Thankfully, there are various tools available to speed up certain parts of your application, or reduce the number of times these various time-consuming tasks need to run. diff --git a/_posts/14-02-01-Opcode-Cache.md b/_posts/14-02-01-Opcode-Cache.md index 6a93de5..c4be0b1 100644 --- a/_posts/14-02-01-Opcode-Cache.md +++ b/_posts/14-02-01-Opcode-Cache.md @@ -1,25 +1,34 @@ --- isChild: true -anchor: opcode_cache +anchor: opcode_cache --- ## Opcode Cache {#opcode_cache_title} When a PHP file is executed, under the hood it is first compiled to opcodes and, only then, the opcodes are executed. -If a PHP file is not modified, the opcodes will always be the same. This means that the compilation step is a waste of CPU resources. +If a PHP file is not modified, the opcodes will always be the same. This means that the compilation step is a waste of +CPU resources. -This is where opcode caches come in. They prevent redundant compilation by storing opcodes in memory and reusing it on successive calls. -Setting up an opcode cache takes a matter of minutes, and your application will speed up significantly. There's really no reason not to use it. +This is where opcode caches come in. They prevent redundant compilation by storing opcodes in memory and reusing it on +successive calls. Setting up an opcode cache takes a matter of minutes, and your application will speed up +significantly. There's really no reason not to use it. -As of PHP 5.5, there is a built-in opcode cache called [OPcache][opcache-book]. It is also available for earlier versions. +As of PHP 5.5, there is a built-in opcode cache called [OPcache][opcache-book]. It is also available for earlier +versions. Read more about opcode caches: * [OPcache][opcache-book] (built-in since PHP 5.5) -* [APC](http://php.net/manual/en/book.apc.php) (PHP 5.4 and earlier) -* [XCache](http://xcache.lighttpd.net/) -* [Zend Optimizer+](http://www.zend.com/products/server/) (part of Zend Server package) -* [WinCache](http://www.iis.net/download/wincacheforphp) (extension for MS Windows Server) -* [list of PHP accelerators on Wikipedia](http://en.wikipedia.org/wiki/List_of_PHP_accelerators) +* [APC] (PHP 5.4 and earlier) +* [XCache] +* [Zend Optimizer+] (part of Zend Server package) +* [WinCache] (extension for MS Windows Server) +* [list of PHP accelerators on Wikipedia][PHP_accelerators] -[opcache-book]: http://php.net/manual/en/book.opcache.php \ No newline at end of file + +[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 \ No newline at end of file diff --git a/_posts/14-03-01-Object-Caching.md b/_posts/14-03-01-Object-Caching.md index 7fabfa9..7dc9a77 100644 --- a/_posts/14-03-01-Object-Caching.md +++ b/_posts/14-03-01-Object-Caching.md @@ -1,6 +1,6 @@ --- isChild: true -anchor: object_caching +anchor: object_caching --- ## Object Caching {#object_caching_title} @@ -16,17 +16,17 @@ advantage of them. APCu, XCache, and WinCache all provide APIs to save data from The most commonly used memory object caching systems are APCu and memcached. APCu is an excellent choice for object caching, it includes a simple API for adding your own data to its memory cache and is very easy to setup and use. The -one real limitation of APCu is that it is tied to the server it's installed on. Memcached on the other hand is installed -as a separate service and can be accessed across the network, meaning that you can store objects in a hyper-fast data -store in a central location and many different systems can pull from it. +one real limitation of APCu is that it is tied to the server it's installed on. Memcached on the other hand is +installed as a separate service and can be accessed across the network, meaning that you can store objects in a +hyper-fast data store in a central location and many different systems can pull from it. -Note that when running PHP as a (Fast-)CGI application inside your webserver, every PHP process will have its own -cache, i.e. APCu data is not shared between your worker processes. In these cases, you might want to consider using -memcached instead, as it's not tied to the PHP processes. +Note that when running PHP as a (Fast-)CGI application inside your webserver, every PHP process will have its own cache, +i.e. APCu data is not shared between your worker processes. In these cases, you might want to consider using memcached +instead, as it's not tied to the PHP processes. -In a networked configuration APCu will usually outperform memcached in terms of access speed, but memcached will be able -to scale up faster and further. If you do not expect to have multiple servers running your application, or do not need -the extra features that memcached offers then APCu is probably your best choice for object caching. +In a networked configuration APCu will usually outperform memcached in terms of access speed, but memcached will be +able to scale up faster and further. If you do not expect to have multiple servers running your application, or do not +need the extra features that memcached offers then APCu is probably your best choice for object caching. Example logic using APCu: @@ -45,11 +45,11 @@ print_r($data); Note that prior to PHP 5.5, APC provides both an object cache and a bytecode cache. APCu is a project to bring APC's object cache to PHP 5.5+, since PHP now has a built-in bytecode cache (OPcache). -Learn more about popular object caching systems: +### Learn more about popular object caching systems: * [APCu](https://github.com/krakjoe/apcu) -* [APC Functions](http://php.net/manual/en/ref.apc.php) +* [APC Functions](http://php.net/ref.apc) * [Memcached](http://memcached.org/) * [Redis](http://redis.io/) * [XCache APIs](http://xcache.lighttpd.net/wiki/XcacheApi) -* [WinCache Functions](http://www.php.net/manual/en/ref.wincache.php) +* [WinCache Functions](http://php.net/ref.wincache) diff --git a/_posts/15-01-01-Documenting.md b/_posts/15-01-01-Documenting.md new file mode 100644 index 0000000..ea009bd --- /dev/null +++ b/_posts/15-01-01-Documenting.md @@ -0,0 +1,6 @@ +--- +anchor: documenting +title: Documenting your Code +--- + +# Documenting your Code {#documenting_title} diff --git a/_posts/15-01-01-Resources.md b/_posts/15-01-01-Resources.md deleted file mode 100644 index 06c3b2e..0000000 --- a/_posts/15-01-01-Resources.md +++ /dev/null @@ -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/) diff --git a/_posts/15-02-01-Frameworks.md b/_posts/15-02-01-Frameworks.md deleted file mode 100644 index b2ea122..0000000 --- a/_posts/15-02-01-Frameworks.md +++ /dev/null @@ -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) \ No newline at end of file diff --git a/_posts/15-02-01-PHPDoc.md b/_posts/15-02-01-PHPDoc.md new file mode 100644 index 0000000..cfbc758 --- /dev/null +++ b/_posts/15-02-01-PHPDoc.md @@ -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 %} + + * @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 diff --git a/_posts/15-03-01-Components.md b/_posts/15-03-01-Components.md deleted file mode 100644 index b680917..0000000 --- a/_posts/15-03-01-Components.md +++ /dev/null @@ -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._ diff --git a/_posts/15-04-01-Books.md b/_posts/15-04-01-Books.md deleted file mode 100644 index 8229067..0000000 --- a/_posts/15-04-01-Books.md +++ /dev/null @@ -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. diff --git a/_posts/16-01-01-Community.md b/_posts/16-01-01-Community.md deleted file mode 100644 index e89f9c8..0000000 --- a/_posts/16-01-01-Community.md +++ /dev/null @@ -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 diff --git a/_posts/16-01-01-Resources.md b/_posts/16-01-01-Resources.md new file mode 100644 index 0000000..7747724 --- /dev/null +++ b/_posts/16-01-01-Resources.md @@ -0,0 +1,5 @@ +--- +anchor: resources +--- + +# Resources {#resources_title} diff --git a/_posts/16-02-01-From-the-Source.md b/_posts/16-02-01-From-the-Source.md new file mode 100644 index 0000000..473798e --- /dev/null +++ b/_posts/16-02-01-From-the-Source.md @@ -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) diff --git a/_posts/16-03-01-People-to-Follow.md b/_posts/16-03-01-People-to-Follow.md new file mode 100644 index 0000000..7a692cc --- /dev/null +++ b/_posts/16-03-01-People-to-Follow.md @@ -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) diff --git a/_posts/16-04-01-Mentoring.md b/_posts/16-04-01-Mentoring.md new file mode 100644 index 0000000..1d7ddc1 --- /dev/null +++ b/_posts/16-04-01-Mentoring.md @@ -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. diff --git a/_posts/16-05-01-PHP-PaaS-Providers.md b/_posts/16-05-01-PHP-PaaS-Providers.md new file mode 100644 index 0000000..8f57dcc --- /dev/null +++ b/_posts/16-05-01-PHP-PaaS-Providers.md @@ -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/) diff --git a/_posts/16-06-01-Frameworks.md b/_posts/16-06-01-Frameworks.md new file mode 100644 index 0000000..63c27b2 --- /dev/null +++ b/_posts/16-06-01-Frameworks.md @@ -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) \ No newline at end of file diff --git a/_posts/16-07-01-Components.md b/_posts/16-07-01-Components.md new file mode 100644 index 0000000..2e57b91 --- /dev/null +++ b/_posts/16-07-01-Components.md @@ -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 diff --git a/_posts/16-08-01-Books.md b/_posts/16-08-01-Books.md new file mode 100644 index 0000000..3af7d0c --- /dev/null +++ b/_posts/16-08-01-Books.md @@ -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. diff --git a/_posts/17-01-01-Community.md b/_posts/17-01-01-Community.md new file mode 100644 index 0000000..82be581 --- /dev/null +++ b/_posts/17-01-01-Community.md @@ -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 diff --git a/_posts/17-01-01-PHPDoc.md b/_posts/17-01-01-PHPDoc.md deleted file mode 100644 index 21f4dfa..0000000 --- a/_posts/17-01-01-PHPDoc.md +++ /dev/null @@ -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 %} - - * @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. diff --git a/_posts/17-02-01-User-Groups.md b/_posts/17-02-01-User-Groups.md new file mode 100644 index 0000000..48d8f83 --- /dev/null +++ b/_posts/17-02-01-User-Groups.md @@ -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 diff --git a/_posts/17-03-01-Conferences.md b/_posts/17-03-01-Conferences.md new file mode 100644 index 0000000..902f1ca --- /dev/null +++ b/_posts/17-03-01-Conferences.md @@ -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 diff --git a/pages/Design-Patterns.md b/pages/Design-Patterns.md index 78255cf..7e57cb9 100644 --- a/pages/Design-Patterns.md +++ b/pages/Design-Patterns.md @@ -1,13 +1,13 @@ --- layout: page -title: Design Patterns +title: Design Patterns --- # Design Patterns -There are numerous ways to structure the code and project for your web application, and you can put as much or as little -thought as you like into architecting. But it is usually a good idea to follow common patterns because it will make -your code easier to manage and easier for others to understand. +There are numerous ways to structure the code and project for your web application, and you can put as much or as +little thought as you like into architecting. But it is usually a good idea to follow common patterns because it will +make your code easier to manage and easier for others to understand. * [Architectural pattern on Wikipedia](https://en.wikipedia.org/wiki/Architectural_pattern) * [Software design pattern on Wikipedia](https://en.wikipedia.org/wiki/Software_design_pattern) @@ -15,8 +15,8 @@ your code easier to manage and easier for others to understand. ## Factory -One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates -the object you want to use. Consider the following example of the factory pattern: +One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the +object you want to use. Consider the following example of the factory pattern: {% highlight php %} getMakeAndModel()); // outputs "Bugatti Veyron" This code uses a factory to create the Automobile object. There are two possible benefits to building your code this way; the first is that if you need to change, rename, or replace the Automobile class later on you can do so and you -will only have to modify the code in the factory, instead of every place in your project that uses the Automobile -class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in -the factory, instead of repeating it every time you want to create a new instance. +will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class. +The second possible benefit is that if creating the object is a complicated job you can do all of the work in the +factory, instead of repeating it every time you want to create a new instance. Using the factory pattern isn't always necessary (or wise). The example code used here is so simple that a factory would simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save @@ -65,8 +65,8 @@ yourself a lot of trouble down the road by using factories. ## Singleton -When designing web applications, it often makes sense conceptually and architecturally to allow access to one and -only one instance of a particular class. The singleton pattern enables us to do this. +When designing web applications, it often makes sense conceptually and architecturally to allow access to one and only +one instance of a particular class. The singleton pattern enables us to do this. {% highlight php %} 3 {% endhighlight %} -Each filter function in the family accepts only elements greater than some minimum value. Single filter returned by -`criteria_greater_than` is a closure with `$min` argument closed by the value in the scope (given as an argument when +Each filter function in the family accepts only elements greater than some minimum value. Single filter returned by +`criteria_greater_than` is a closure with `$min` argument closed by the value in the scope (given as an argument when `criteria_greater_than` is called). Early binding is used by default for importing `$min` variable into the created function. For true closures with late -binding one should use a reference when importing. Imagine a templating or input validation library, where closure is +binding one should use a reference when importing. Imagine a templating or input validation library, where closure is defined to capture variables in scope and access them later when the anonymous function is evaluated. * [Read about Anonymous functions][anonymous-functions] * [More details in the Closures RFC][closures-rfc] -* [Read about dynamically invoking functions with `call_user_func_array`][call-user-func-array] +* [Read about dynamically invoking functions with `call_user_func_array()`][call-user-func-array] -[anonymous-functions]: http://www.php.net/manual/en/functions.anonymous.php -[call-user-func-array]: http://php.net/manual/en/function.call-user-func-array.php + +[anonymous-functions]: http://php.net/functions.anonymous [closures-rfc]: https://wiki.php.net/rfc/closures +[call-user-func-array]: http://php.net/function.call-user-func-array diff --git a/pages/The-Basics.md b/pages/The-Basics.md index 055bf42..75221e3 100644 --- a/pages/The-Basics.md +++ b/pages/The-Basics.md @@ -1,6 +1,6 @@ --- layout: page -title: The Basics +title: The Basics --- # The Basics @@ -33,8 +33,8 @@ if (strpos('testing', 'test') !== false) { // true, as strict comparison was } {% endhighlight %} -* [Comparison operators](http://php.net/manual/en/language.operators.comparison.php) -* [Comparison table](http://php.net/manual/en/types.comparisons.php) +* [Comparison operators](http://php.net/language.operators.comparison) +* [Comparison table](http://php.net/types.comparisons) ## Conditional statements @@ -66,7 +66,7 @@ function test($a) } {% endhighlight %} -* [If statements](http://php.net/manual/en/control-structures.if.php) +* [If statements](http://php.net/control-structures.if) ### Switch statements @@ -99,13 +99,13 @@ function test($a) } {% endhighlight %} -* [Switch statements](http://php.net/manual/en/control-structures.switch.php) +* [Switch statements](http://php.net/control-structures.switch) * [PHP switch](http://phpswitch.com/) ## Global namespace -When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this, -refer to the global function by using a backslash before the function name. +When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this, refer to +the global function by using a backslash before the function name. {% highlight php %}