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 f6600ae..090e8f2 100644 --- a/_posts/01-02-01-Use-the-Current-Stable-Version.md +++ b/_posts/01-02-01-Use-the-Current-Stable-Version.md @@ -6,7 +6,10 @@ anchor: use_the_current_stable_version ## Use the Current Stable Version (5.6) {#use_the_current_stable_version_title} -If you are getting started with PHP, start with the current stable release of [PHP 5.6][php-release]. PHP has added powerful [new features](#language_highlights) over the last few years. Though the incremental version number difference between 5.2 and 5.6 is small, it represents _major_ improvements. If you are looking for a function or its usage, the documentation on the [php.net][php-docs] website will have the answer. +If you are getting started with PHP, start with the current stable release of [PHP 5.6][php-release]. PHP has added +powerful [new features](#language_highlights) over the last few years. Though the incremental version number difference +between 5.2 and 5.6 is small, it represents _major_ improvements. If you are looking for a function or its usage, the +documentation on the [php.net][php-docs] website will have the answer. [php-release]: http://php.net/downloads.php [php-docs]: http://php.net/manual/ diff --git a/_posts/01-03-01-Built-in-Web-Server.md b/_posts/01-03-01-Built-in-Web-Server.md index 8513a85..2a3e154 100644 --- a/_posts/01-03-01-Built-in-Web-Server.md +++ b/_posts/01-03-01-Built-in-Web-Server.md @@ -6,7 +6,8 @@ anchor: builtin_web_server ## Built-in web server {#builtin_web_server_title} -With PHP 5.4 or newer, you can start learning PHP without installing and configuring a full-fledged web server. To start the server, run the following command from your terminal in your project's web root: +With PHP 5.4 or newer, you can start learning PHP without installing and configuring a full-fledged web server. +To start the server, run the following command from your terminal in your project's web root: {% highlight console %} > php -S localhost:8000 diff --git a/_posts/01-04-01-Mac-Setup.md b/_posts/01-04-01-Mac-Setup.md index c4f8b7b..471c2fa 100644 --- a/_posts/01-04-01-Mac-Setup.md +++ b/_posts/01-04-01-Mac-Setup.md @@ -3,35 +3,38 @@ isChild: true anchor: mac_setup --- -## Mac Setup {#mac_setup_title} +## Mac Setup {#mac_setup_title} -OS X comes prepackaged with PHP but it is normally a little behind the latest stable. Mountain Lion has -5.3.10, Mavericks has 5.4.17 and Yosemite has 5.5.9, but with PHP 5.6 out that is often not good enough. +OS X comes prepackaged with PHP but it is normally a little behind the latest stable. Mountain Lion has 5.3.10, +Mavericks has 5.4.17 and Yosemite has 5.5.9, but with PHP 5.6 out that is often not good enough. There are multiple ways to install PHP on OS X. ### Install PHP via Homebrew -[Homebrew](http://brew.sh/) is a powerful package manager for OS X, which can help you install PHP and -various extensions easily. [Homebrew PHP] is a repository that contains PHP-related "formulae" for Homebrew, -and will let you install PHP. +[Homebrew](http://brew.sh/) is a powerful package manager for OS X, which can help you install PHP and various +extensions easily. [Homebrew PHP] is a repository that contains PHP-related "formulae" for Homebrew, and will let you +install PHP. -At this point, you can install `php53`, `php54`, `php55` or `php56` using the `brew install` command, and switch between them by modifying your `PATH` variable. +At this point, you can install `php53`, `php54`, `php55` or `php56` using the `brew install` command, and switch +between them by modifying your `PATH` variable. ### Install PHP via phpbrew -[phpbrew] is a tool for installing and managing multiple PHP versions. This can be really useful if two -different applications/projects require different versions of PHP, and you are not using virtual machines. +[phpbrew] is a tool for installing and managing multiple PHP versions. This can be really useful if two different +applications/projects require different versions of PHP, and you are not using virtual machines. ### Compile from Source -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"] +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. -### 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 diff --git a/_posts/01-05-01-Windows-Setup.md b/_posts/01-05-01-Windows-Setup.md index 6094516..1a56bf2 100644 --- a/_posts/01-05-01-Windows-Setup.md +++ b/_posts/01-05-01-Windows-Setup.md @@ -5,18 +5,19 @@ anchor: windows_setup ## Windows Setup {#windows_setup_title} -PHP is available in several ways for Windows. You can [download the binaries][php-downloads] and until recently you could use a '.msi' -installer. The installer is no longer supported and stops at PHP 5.3.0. +PHP is available in several ways for Windows. You can [download the binaries][php-downloads] and until recently you +could use a '.msi' installer. The installer is no longer supported and stops at PHP 5.3.0. -For learning and local development you can use the built in webserver with PHP 5.4+ so you don't need to worry about configuring it. If you -would like an "all-in-one" which includes a full-blown webserver and MySQL too then tools such as the [Web Platform Installer][wpi], -[Zend Server CE][zsce], [XAMPP][xampp], [EasyPHP][easyphp] and [WAMP][wamp] will help get a Windows development environment up and running fast. That said, these tools will be -a little different from production so be careful of environment differences if you are working on Windows and deploying to Linux. +For learning and local development you can use the built in webserver with PHP 5.4+ so you don't need to worry about +configuring it. If you would like an "all-in-one" which includes a full-blown webserver and MySQL too then tools such +as the [Web Platform Installer][wpi], [Zend Server CE][zsce], [XAMPP][xampp], [EasyPHP][easyphp] and [WAMP][wamp] will +help get a Windows development environment up and running fast. That said, these tools will be a little different from +production so be careful of environment differences if you are working on Windows and deploying to Linux. -If you need to run your production system on Windows then IIS7 will give you the most stable and best performance. You can use -[phpmanager][phpmanager] (a GUI plugin for IIS7) to make configuring and managing PHP simple. IIS7 comes with FastCGI built in and ready -to go, you just need to configure PHP as a handler. For support and additional resources there is a [dedicated area on iis.net][php-iis] for -PHP. +If you need to run your production system on Windows then IIS7 will give you the most stable and best performance. You +can use [phpmanager][phpmanager] (a GUI plugin for IIS7) to make configuring and managing PHP simple. IIS7 comes with +FastCGI built in and ready to go, you just need to configure PHP as a handler. For support and additional resources +there is a [dedicated area on iis.net][php-iis] for PHP. [php-downloads]: http://windows.php.net [phpmanager]: http://phpmanager.codeplex.com/ diff --git a/_posts/02-01-01-Code-Style-Guide.md b/_posts/02-01-01-Code-Style-Guide.md index 0ab5fd4..8a74cf6 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,17 @@ and applications that implement the components can have consistency even when wo * [Read about Zend Coding Standards][zend-cs] * [Read about Symfony Coding Standards][symfony-cs] -You can use [PHP_CodeSniffer][phpcs] to check code against any one of these recommendations, and plugins for text editors -like [Sublime Text 2][st-cs] to be given real time feedback. +You can use [PHP_CodeSniffer][phpcs] to check code against any one of these recommendations, and plugins for text +editors like [Sublime Text 2][st-cs] to be given real time feedback. You can fix the code layout automatically by using one of the two possible tools. One is Fabien Potencier's -[PHP Coding Standards Fixer][phpcsfixer] which has a very well tested codebase. It is bigger and slower, but very stable -and used by some huge projects like Magento and Symfony. Another option is [php.tools][phptools], which is made popular -by the [sublime-phpfmt][sublime-phpfmt] editor plugin. While being newer, it makes great improvements in performance, -meaning real-time editor fixing is more fluid. +[PHP Coding Standards Fixer][phpcsfixer] which has a very well tested codebase. It is bigger and slower, but very +stable and used by some huge projects like Magento and Symfony. Another option is [php.tools][phptools], which is made +popular by the [sublime-phpfmt][sublime-phpfmt] editor plugin. While being newer, it makes great improvements in +performance, meaning real-time editor fixing is more fluid. -English is preferred for all symbol names and code infrastructure. Comments may be written in any language easily readable -by all current and future parties who may be working on the codebase. +English is preferred for all symbol names and code infrastructure. Comments may be written in any language easily +readable by all current and future parties who may be working on the codebase. [fig]: http://www.php-fig.org/ [psr0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md diff --git a/_posts/03-02-01-Programming-Paradigms.md b/_posts/03-02-01-Programming-Paradigms.md index a69510e..cdc7924 100644 --- a/_posts/03-02-01-Programming-Paradigms.md +++ b/_posts/03-02-01-Programming-Paradigms.md @@ -6,8 +6,8 @@ anchor: programming_paradigms ## Programming Paradigms {#programming_paradigms_title} PHP is a flexible, dynamic language that supports a variety of programming techniques. It has evolved dramatically over -the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in PHP 5.3 -(2009), and traits in PHP 5.4 (2012). +the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in +PHP 5.3 (2009), and traits in PHP 5.4 (2012). ### Object-oriented Programming @@ -19,12 +19,12 @@ interfaces, inheritance, constructors, cloning, exceptions, and more. ### Functional Programming -PHP supports first-class function, meaning that a function can be assigned to a variable. Both user-defined and built-in -functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to other -functions (feature called Higher-order functions) and function can return other functions. +PHP supports first-class function, meaning that a function can be assigned to a variable. Both user-defined and +built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to +other functions (feature called Higher-order functions) and function can return other functions. -Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code focus -on iteration. +Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code +focus on iteration. New anonymous functions (with support for closures) are present since PHP 5.3 (2009). diff --git a/_posts/03-03-01-Namespaces.md b/_posts/03-03-01-Namespaces.md index a9d7c41..1186810 100644 --- a/_posts/03-03-01-Namespaces.md +++ b/_posts/03-03-01-Namespaces.md @@ -5,25 +5,24 @@ anchor: namespaces ## Namespaces {#namespaces_title} -As mentioned above, the PHP community has a lot of developers creating lots of code. This means that -one library's PHP code may use the same class name as another library. When both libraries are used -in the same namespace, they collide and cause trouble. +As mentioned above, the PHP community has a lot of developers creating lots of code. This means that one library's PHP +code may use the same class name as another library. When both libraries are used in the same namespace, they collide +and cause trouble. -_Namespaces_ solve this problem. As described in the PHP reference manual, namespaces may be compared -to operating system directories that _namespace_ files; two files with the same name may co-exist in -separate directories. Likewise, two PHP classes with the same name may co-exist in separate PHP -namespaces. It's as simple as that. +_Namespaces_ solve this problem. As described in the PHP reference manual, namespaces may be compared to operating +system directories that _namespace_ files; two files with the same name may co-exist in separate directories. Likewise, +two PHP classes with the same name may co-exist in separate PHP namespaces. It's as simple as that. -It is important for you to namespace your code so that it may be used by other developers without fear -of colliding with other libraries. +It is important for you to namespace your code so that it may be used by other developers without fear of colliding +with other libraries. -One recommended way to use namespaces is outlined in [PSR-0][psr0], which aims to provide a standard file, -class and namespace convention to allow plug-and-play code. +One recommended way to use namespaces is outlined in [PSR-0][psr0], which aims to provide a standard file, class and +namespace convention to allow plug-and-play code. -In December 2013 the PHP-FIG created a new autoloading standard: [PSR-4][psr4], which one day will -probably replace PSR-0. Currently both are still usable, as PSR-4 requires PHP 5.3 and many PHP 5.2-only -projects currently implement PSR-0. If you're going to use an autoloader standard for a new application or -package then you almost certainly want to look into PSR-4. +In December 2013 the PHP-FIG created a new autoloading standard: [PSR-4][psr4], which one day will probably replace +PSR-0. Currently both are still usable, as PSR-4 requires PHP 5.3 and many PHP 5.2-only projects currently implement +PSR-0. If you're going to use an autoloader standard for a new application or package then you almost certainly want +to look into PSR-4. * [Read about Namespaces][namespaces] * [Read about PSR-0][psr0] diff --git a/_posts/03-04-01-Standard-PHP-Library.md b/_posts/03-04-01-Standard-PHP-Library.md index 2d59663..ab26f88 100644 --- a/_posts/03-04-01-Standard-PHP-Library.md +++ b/_posts/03-04-01-Standard-PHP-Library.md @@ -6,7 +6,9 @@ anchor: standard_php_library ## Standard PHP Library {#standard_php_library_title} -The Standard PHP Library (SPL) is packaged with PHP and provides a collection of classes and interfaces. It is made up primarily of commonly needed datastructure classes (stack, queue, heap, and so on), and iterators which can traverse over these datastructures or your own classes which implement SPL interfaces. +The Standard PHP Library (SPL) is packaged with PHP and provides a collection of classes and interfaces. It is made up +primarily of commonly needed datastructure classes (stack, queue, heap, and so on), and iterators which can traverse +over these datastructures or your own classes which implement SPL interfaces. * [Read about the SPL][spl] diff --git a/_posts/03-05-01-Command-Line-Interface.md b/_posts/03-05-01-Command-Line-Interface.md index f0fd756..7f700b9 100644 --- a/_posts/03-05-01-Command-Line-Interface.md +++ b/_posts/03-05-01-Command-Line-Interface.md @@ -5,9 +5,11 @@ anchor: command_line_interface ## Command Line Interface {#command_line_interface_title} -PHP was created to write web applications, but is also useful for scripting command line interface (CLI) programs. Command line PHP programs can help automate common tasks like testing, deployment, and application administrivia. +PHP was created to write web applications, but is also useful for scripting command line interface (CLI) programs. +Command line PHP programs can help automate common tasks like testing, deployment, and application administrivia. -CLI PHP programs are powerful because you can use your app's code directly without having to create and secure a web GUI for it. Just be sure not to put your CLI PHP scripts in your public web root! +CLI PHP programs are powerful because you can use your app's code directly without having to create and secure a web +GUI for it. Just be sure not to put your CLI PHP scripts in your public web root! Try running PHP from your command line: @@ -15,9 +17,10 @@ Try running PHP from your command line: > 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,9 +34,12 @@ $name = $argv[1]; echo "Hello, $name\n"; {% endhighlight %} -PHP sets up two special variables based on the arguments your script is run with. [`$argc`][argc] is an integer variable containing the argument *count* and [`$argv`][argv] is an array variable containing each argument's *value*. The first argument is always the name of your PHP script file, in this case `hello.php`. +PHP sets up two special variables based on the arguments your script is run with. [`$argc`][argc] is an integer +variable containing the argument *count* and [`$argv`][argv] is an array variable containing each argument's *value*. +The first argument is always the name of your PHP script file, in this case `hello.php`. -The `exit()` expression is used with a non-zero number to let the shell know that the command failed. Commonly used exit codes can be found [here][exit-codes] +The `exit()` expression is used with a non-zero number to let the shell know that the command failed. Commonly used +exit codes can be found [here][exit-codes] To run our script, above, from the command line: diff --git a/_posts/03-06-01-XDebug.md b/_posts/03-06-01-XDebug.md index 598b5b4..47489c9 100644 --- a/_posts/03-06-01-XDebug.md +++ b/_posts/03-06-01-XDebug.md @@ -8,15 +8,15 @@ anchor: xdebug One of the most useful tools in software development is a proper debugger. It allows you to trace the execution of your code and monitor the contents of the stack. XDebug, PHP's debugger, can be utilized by various IDEs to provide -Breakpoints and stack inspection. It can also allow tools like PHPUnit and KCacheGrind to perform code coverage analysis -and code profiling. +Breakpoints and stack inspection. It can also allow tools like PHPUnit and KCacheGrind to perform code coverage +analysis and code profiling. -If you find yourself in a bind, willing to resort to var_dump/print_r, and you still can't find the solution - maybe you -need to use the debugger. +If you find yourself in a bind, willing to resort to var_dump/print_r, and you still can't find the solution - maybe +you need to use the debugger. -[Installing XDebug][xdebug-install] can be tricky, but one of its most important features is "Remote Debugging" - if you -develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you will -want to enable right away. +[Installing XDebug][xdebug-install] can be tricky, but one of its most important features is "Remote Debugging" - if +you develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you +will want to enable right away. Traditionally, you will modify your Apache VHost or .htaccess file with these values: @@ -33,8 +33,8 @@ 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] diff --git a/_posts/04-01-01-Dependency-Management.md b/_posts/04-01-01-Dependency-Management.md index 95be994..8309687 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. -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 497ffb1..401ae51 100644 --- a/_posts/04-02-01-Composer-and-Packagist.md +++ b/_posts/04-02-01-Composer-and-Packagist.md @@ -5,26 +5,35 @@ anchor: composer_and_packagist ## Composer and Packagist {#composer_and_packagist_title} -Composer is a **brilliant** dependency manager for PHP. List your project's dependencies in a `composer.json` file and, with a few simple commands, Composer will automatically download your project's dependencies and setup autoloading for you. +Composer is a **brilliant** dependency manager for PHP. List your project's dependencies in a `composer.json` file and, +with a few simple commands, Composer will automatically download your project's dependencies and setup autoloading for +you. -There are already a lot of PHP libraries that are compatible with Composer, ready to be used in your project. These "packages" are listed on [Packagist][1], the official repository for Composer-compatible PHP libraries. +There are already a lot of PHP libraries that are compatible with Composer, ready to be used in your project. These +"packages" are listed on [Packagist][1], the official repository for Composer-compatible PHP libraries. ### How to Install Composer -You can install Composer locally (in your current working directory; though this is no longer recommended) or globally (e.g. /usr/local/bin). Let's assume you want to install Composer locally. From your project's root directory: +You can install Composer locally (in your current working directory; though this is no longer recommended) or globally +(e.g. /usr/local/bin). Let's assume you want to install Composer locally. From your project's root directory: {% highlight console %} curl -s https://getcomposer.org/installer | php {% endhighlight %} -This will download `composer.phar` (a PHP binary archive). You can run this with `php` to manage your project dependencies. 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 @@ -32,16 +41,19 @@ Manually installing Composer is an advanced technique; however, there are variou - certain problematic extensions are not loaded - certain `php.ini` settings are set -Since a manual installation performs none of these checks, you have to decide whether the trade-off is worth it for you. As such, below is how to obtain Composer manually: +Since a manual installation performs none of these checks, you have to decide whether the trade-off is worth it for +you. As such, below is how to obtain Composer manually: {% highlight console %} curl -s https://getcomposer.org/composer.phar -o $HOME/local/bin/composer chmod +x $HOME/local/bin/composer {% endhighlight %} -The path `$HOME/local/bin` (or a directory of your choice) should be in your `$PATH` environment variable. This will result in a `composer` command being available. +The path `$HOME/local/bin` (or a directory of your choice) should be in your `$PATH` environment variable. This will +result in a `composer` command being available. -When you come across documentation that states to run Composer as `php composer.phar install`, you can substitute that with: +When you come across documentation that states to run Composer as `php composer.phar install`, you can substitute that +with: {% highlight console %} composer install @@ -51,19 +63,25 @@ This section will assume you have installed composer globally. ### How to Define and Install Dependencies -Composer keeps track of your project's dependencies in a file called `composer.json`. You can manage it by hand if you like, or use Composer itself. The `composer require` command adds a project dependency and if you don't have a `composer.json` file, one will be created. Here's an example that adds [Twig][2] as a dependency of your project. +Composer keeps track of your project's dependencies in a file called `composer.json`. You can manage it by hand if you +like, or use Composer itself. The `composer require` command adds a project dependency and if you don't have a +`composer.json` file, one will be created. Here's an example that adds [Twig][2] as a dependency of your project. {% highlight console %} composer require twig/twig:~1.8 {% endhighlight %} -Alternatively the `composer init` command will guide you through creating a full `composer.json` file for your project. Either way, once you've created your `composer.json` file you can tell Composer to download and install your dependencies into the `vendor/` directory. This also applies to projects you've downloaded that already provide a `composer.json` file: +Alternatively the `composer init` command will guide you through creating a full `composer.json` file for your project. +Either way, once you've created your `composer.json` file you can tell Composer to download and install your +dependencies into the `vendor/` directory. This also applies to projects you've downloaded that already provide a +`composer.json` file: {% highlight console %} composer install {% endhighlight %} -Next, add this line to your application's primary PHP file; this will tell PHP to use Composer's autoloader for your project dependencies. +Next, add this line to your application's primary PHP file; this will tell PHP to use Composer's autoloader for your +project dependencies. {% highlight php %} 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 diff --git a/_posts/05-02-01-The-Basics.md b/_posts/05-02-01-The-Basics.md index 78df40f..2097b57 100644 --- a/_posts/05-02-01-The-Basics.md +++ b/_posts/05-02-01-The-Basics.md @@ -5,9 +5,9 @@ anchor: the_basics ## The Basics {#the_basics_title} -PHP is a vast language that allows coders of all levels the ability to produce code not only quickly, but efficiently. -However while advancing through the language, we often forget the basics that we first learnt (or overlooked) in favor -of short cuts and/or bad habits. To help combat this common issue, this section is aimed at reminding coders of the +PHP is a vast language that allows coders of all levels the ability to produce code not only quickly, but efficiently. +However while advancing through the language, we often forget the basics that we first learnt (or overlooked) in favor +of short cuts and/or bad habits. To help combat this common issue, this section is aimed at reminding coders of the basic coding practices within PHP. * Continue reading on [The Basics](/pages/The-Basics.html) \ No newline at end of file diff --git a/_posts/05-03-01-Date-and-Time.md b/_posts/05-03-01-Date-and-Time.md index 043f02a..096e2ef 100644 --- a/_posts/05-03-01-Date-and-Time.md +++ b/_posts/05-03-01-Date-and-Time.md @@ -5,13 +5,14 @@ anchor: date_and_time ## Date and Time {#date_and_time_title} -PHP has a class named DateTime to help you when reading, writing, comparing or calculating with date and time. There are -many date and time related functions in PHP besides DateTime, but it provides nice object-oriented interface to most -common uses. It can handle time zones, but that is outside this short introduction. +PHP has a class named DateTime to help you when reading, writing, comparing or calculating with date and time. There +are many date and time related functions in PHP besides DateTime, but it provides nice object-oriented interface to +most common uses. It can handle time zones, but that is outside this short introduction. To start working with DateTime, convert raw date and time string to an object with `createFromFormat()` factory method or do `new DateTime` to get the current date and time. Use `format()` method to convert DateTime back to a string for output. + {% highlight php %} format('Y-m-d') . "\n"; Calculating with DateTime is possible with the DateInterval class. DateTime has methods like `add()` and `sub()` that take a DateInterval as an argument. Do not write code that expect same number of seconds in every day, both daylight -saving and timezone alterations will break that assumption. Use date intervals instead. To calculate date difference use -the `diff()` method. It will return new DateInterval, which is super easy to display. +saving and timezone alterations will break that assumption. Use date intervals instead. To calculate date difference +use the `diff()` method. It will return new DateInterval, which is super easy to display. + {% highlight php %} format('%m month, %d days (total: %a days)') . "\n" {% endhighlight %} On DateTime objects you can use standard comparison: + {% highlight php %} ` 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 %} 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..fb875e8 100644 --- a/_posts/06-02-01-Basic-Concept.md +++ b/_posts/06-02-01-Basic-Concept.md @@ -7,9 +7,9 @@ anchor: basic_concept We can demonstrate the concept with a simple, yet naive example. -Here we have a `Database` class that requires an adapter to speak to the database. We instantiate the -adapter in the constructor and create a hard dependency. This makes testing difficult and means the `Database` class is -very tightly coupled to the adapter. +Here we have a `Database` class that requires an adapter to speak to the database. We instantiate the adapter in the +constructor and create a hard dependency. This makes testing difficult and means the `Database` class is very tightly +coupled to the adapter. {% highlight php %} fetch(PDO::FETCH_ASSOC); echo htmlentities($row['some_field']); {% endhighlight %} -PDO will not translate your SQL queries or emulate missing features; it is purely for connecting to multiple types -of database with the same API. +PDO will not translate your SQL queries or emulate missing features; it is purely for connecting to multiple types of +database with the same API. -More importantly, `PDO` allows you to safely inject foreign input (e.g. IDs) into your SQL queries without worrying about database SQL injection attacks. +More importantly, `PDO` allows you to safely inject foreign input (e.g. IDs) into your SQL queries without worrying +about database SQL injection attacks. This is possible using PDO statements and bound parameters. -Let's assume a PHP script receives a numeric ID as a query parameter. This ID should be used to fetch a user record from a database. This is the `wrong` -way to do this: +Let's assume a PHP script receives a numeric ID as a query parameter. This ID should be used to fetch a user record +from a database. This is the `wrong` way to do this: {% highlight php %} query("SELECT name FROM users WHERE id = " . $_GET['id']); // <-- NO! {% endhighlight %} This is terrible code. You are inserting a raw query parameter into a SQL query. This will get you hacked in a -heartbeat, using a practice called [SQL Injection](http://wiki.hashphp.org/Validation). Just imagine if a hacker passes in an inventive `id` parameter by calling a URL like -`http://domain.com/?id=1%3BDELETE+FROM+users`. This will set the `$_GET['id']` variable to `1;DELETE FROM users` -which will delete all of your users! Instead, you should sanitize the ID input using PDO bound parameters. +heartbeat, using a practice called [SQL Injection](http://wiki.hashphp.org/Validation). Just imagine if a hacker +passes in an inventive `id` parameter by calling a URL like `http://domain.com/?id=1%3BDELETE+FROM+users`. This will +set the `$_GET['id']` variable to `1;DELETE FROM users` which will delete all of your users! Instead, you should +sanitize the ID input using PDO bound parameters. {% highlight php %} bindParam(':id', $_GET['id'], PDO::PARAM_INT); // <-- Automatically sanit $stmt->execute(); {% endhighlight %} -This is correct code. It uses a bound parameter on a PDO statement. This escapes the foreign input ID before it is introduced to the -database preventing potential SQL injection attacks. +This is correct code. It uses a bound parameter on a PDO statement. This escapes the foreign input ID before it is +introduced to the database preventing potential SQL injection attacks. * [Learn about PDO] You should also be aware that database connections use up resources and it was not unheard-of to have resources -exhausted if connections were not implicitly closed, however this was more common in other languages. Using PDO you -can implicitly close the connection by destroying the object by ensuring all remaining references to it are deleted, -i.e. set to NULL. If you don't do this explicitly, PHP will automatically close the connection when your script ends - +exhausted if connections were not implicitly closed, however this was more common in other languages. Using PDO you can +implicitly close the connection by destroying the object by ensuring all remaining references to it are deleted, i.e. +set to NULL. If you don't do this explicitly, PHP will automatically close the connection when your script ends - unless of course you are using persistent connections. * [Learn about PDO connections] diff --git a/_posts/07-02-01-Interacting-via-Code.md b/_posts/07-02-01-Interacting-via-Code.md index df8dc48..a8d2e57 100644 --- a/_posts/07-02-01-Interacting-via-Code.md +++ b/_posts/07-02-01-Interacting-via-Code.md @@ -6,7 +6,7 @@ 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,7 +40,9 @@ foreach (getAllFoos($db) as $row) { That is a good start. Put those two items in two different files and you've got some clean separation. -Create a class to place that method in and you have a "Model". Create a simple `.php` file to put the presentation logic in and you have a "View", which is very nearly [MVC] - a common OOP architecture for most [frameworks](/#frameworks_title). +Create a class to place that method in and you have a "Model". Create a simple `.php` file to put the presentation +logic in and you have a "View", which is very nearly [MVC] - a common OOP architecture for most +[frameworks](/#frameworks_title). **foo.php** @@ -84,11 +88,12 @@ class Foo() {% 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-03-01-Abstraction-Layers.md b/_posts/07-03-01-Abstraction-Layers.md index 6379341..849498b 100644 --- a/_posts/07-03-01-Abstraction-Layers.md +++ b/_posts/07-03-01-Abstraction-Layers.md @@ -6,12 +6,14 @@ anchor: databases_abstraction_layers ## Abstraction Layers {#databases_abstraction_layers_title} -Many frameworks provide their own abstraction layer which may or may not sit on top of PDO. These will often emulate features for -one database system that is missing from another by wrapping your queries in PHP methods, giving you actual database abstraction instead of just the connection abstraction that PDO provides. -This will of course add a little overhead, but if you are building a portable application that needs to work with MySQL, PostgreSQL and -SQLite then a little overhead will be worth it the sake of code cleanliness. +Many frameworks provide their own abstraction layer which may or may not sit on top of PDO. These will often emulate +features for one database system that is missing from another by wrapping your queries in PHP methods, giving you +actual database abstraction instead of just the connection abstraction that PDO provides. This will of course add a +little overhead, but if you are building a portable application that needs to work with MySQL, PostgreSQL and SQLite +then a little overhead will be worth it the sake of code cleanliness. -Some abstraction layers have been built using the [PSR-0][psr0] or [PSR-4][psr4] namespace standards so can be installed in any application you like: +Some abstraction layers have been built using the [PSR-0][psr0] or [PSR-4][psr4] namespace standards so can be +installed in any application you like: * [Aura SQL][6] * [Doctrine2 DBAL][2] diff --git a/pages/Design-Patterns.md b/pages/Design-Patterns.md index 47f8301..77d0349 100644 --- a/pages/Design-Patterns.md +++ b/pages/Design-Patterns.md @@ -5,9 +5,9 @@ title: Design Patterns # Design Patterns -There are numerous ways to structure the code and project for your web application, and you can put as much or as little -thought as you like into architecting. But it is usually a good idea to follow common patterns because it will make -your code easier to manage and easier for others to understand. +There are numerous ways to structure the code and project for your web application, and you can put as much or as +little thought as you like into architecting. But it is usually a good idea to follow common patterns because it will +make your code easier to manage and easier for others to understand. * [Architectural pattern on Wikipedia](https://en.wikipedia.org/wiki/Architectural_pattern) * [Software design pattern on Wikipedia](https://en.wikipedia.org/wiki/Software_design_pattern) @@ -15,8 +15,8 @@ your code easier to manage and easier for others to understand. ## Factory -One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates -the object you want to use. Consider the following example of the factory pattern: +One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the +object you want to use. Consider the following example of the factory pattern: {% highlight php %} 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] diff --git a/pages/The-Basics.md b/pages/The-Basics.md index 4e785c2..ee8a181 100644 --- a/pages/The-Basics.md +++ b/pages/The-Basics.md @@ -104,8 +104,8 @@ function test($a) ## Global namespace -When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this, -refer to the global function by using a backslash before the function name. +When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this, refer to +the global function by using a backslash before the function name. {% highlight php %}