Merge branch 'gh-pages' into patch-1

This commit is contained in:
Carlos Buenosvinos
2018-06-24 13:22:33 +02:00
committed by GitHub
67 changed files with 720 additions and 621 deletions

2
CNAME
View File

@@ -1 +1 @@
www.phptherightway.com www.phptherightway.com

View File

@@ -1,3 +1,3 @@
source 'https://rubygems.org' source 'https://rubygems.org'
gem 'github-pages' gem 'github-pages', group: :jekyll_plugins
gem 'rouge' gem 'rouge'

View File

@@ -2,57 +2,61 @@ GEM
remote: https://rubygems.org/ remote: https://rubygems.org/
specs: specs:
RedCloth (4.2.9) RedCloth (4.2.9)
activesupport (5.0.0.1) activesupport (5.2.0)
concurrent-ruby (~> 1.0, >= 1.0.2) concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (~> 0.7) i18n (>= 0.7, < 2)
minitest (~> 5.1) minitest (~> 5.1)
tzinfo (~> 1.1) tzinfo (~> 1.1)
addressable (2.4.0) addressable (2.4.0)
blankslate (2.1.2.4) blankslate (2.1.2.4)
classifier-reborn (2.0.4) classifier-reborn (2.2.0)
fast-stemmer (~> 1.0) fast-stemmer (~> 1.0)
coffee-script (2.4.1) coffee-script (2.4.1)
coffee-script-source coffee-script-source
execjs execjs
coffee-script-source (1.10.0) coffee-script-source (1.12.2)
colorator (0.1) colorator (0.1)
concurrent-ruby (1.0.2) concurrent-ruby (1.0.5)
ethon (0.9.1) ethon (0.11.0)
ffi (>= 1.3.0) ffi (>= 1.3.0)
execjs (2.7.0) execjs (2.7.0)
faraday (0.10.0) faraday (0.15.2)
multipart-post (>= 1.2, < 3) multipart-post (>= 1.2, < 3)
fast-stemmer (1.0.2) fast-stemmer (1.0.2)
ffi (1.9.14) ffi (1.9.25)
ffi (1.9.14-x64-mingw32)
gemoji (2.1.0) gemoji (2.1.0)
github-pages (39) github-pages (43)
RedCloth (= 4.2.9) RedCloth (= 4.2.9)
github-pages-health-check (~> 0.2) github-pages-health-check (= 0.6.0)
jekyll (= 2.4.0) jekyll (= 2.4.0)
jekyll-coffeescript (= 1.0.1) jekyll-coffeescript (= 1.0.1)
jekyll-feed (= 0.3.1) jekyll-feed (= 0.3.1)
jekyll-gist (= 1.4.0)
jekyll-mentions (= 0.2.1) jekyll-mentions (= 0.2.1)
jekyll-redirect-from (= 0.8.0) jekyll-paginate (= 1.1.0)
jekyll-redirect-from (= 0.9.1)
jekyll-sass-converter (= 1.3.0) jekyll-sass-converter (= 1.3.0)
jekyll-sitemap (= 0.8.1) jekyll-seo-tag (= 0.1.4)
jekyll-sitemap (= 0.9.0)
jemoji (= 0.5.0) jemoji (= 0.5.0)
kramdown (= 1.5.0) kramdown (= 1.9.0)
liquid (= 2.6.2) liquid (= 2.6.2)
maruku (= 0.7.0) maruku (= 0.7.0)
mercenary (~> 0.3) mercenary (~> 0.3)
pygments.rb (= 0.6.3) pygments.rb (= 0.6.3)
rdiscount (= 2.1.7) rdiscount (= 2.1.8)
redcarpet (= 3.3.2) redcarpet (= 3.3.3)
terminal-table (~> 1.4) terminal-table (~> 1.4)
github-pages-health-check (0.3.2) github-pages-health-check (0.6.0)
net-dns (~> 0.6) addressable (~> 2.3)
net-dns (~> 0.8)
public_suffix (~> 1.4) public_suffix (~> 1.4)
typhoeus (~> 0.7) typhoeus (~> 0.7)
html-pipeline (1.9.0) html-pipeline (1.9.0)
activesupport (>= 2) activesupport (>= 2)
nokogiri (~> 1.4) nokogiri (~> 1.4)
i18n (0.7.0) i18n (1.0.1)
concurrent-ruby (~> 1.0)
jekyll (2.4.0) jekyll (2.4.0)
classifier-reborn (~> 2.0) classifier-reborn (~> 2.0)
colorator (~> 0.1) colorator (~> 0.1)
@@ -77,71 +81,76 @@ GEM
html-pipeline (~> 1.9.0) html-pipeline (~> 1.9.0)
jekyll (~> 2.0) jekyll (~> 2.0)
jekyll-paginate (1.1.0) jekyll-paginate (1.1.0)
jekyll-redirect-from (0.8.0) jekyll-redirect-from (0.9.1)
jekyll (>= 2.0) jekyll (>= 2.0)
jekyll-sass-converter (1.3.0) jekyll-sass-converter (1.3.0)
sass (~> 3.2) sass (~> 3.2)
jekyll-sitemap (0.8.1) jekyll-seo-tag (0.1.4)
jekyll-watch (1.5.0) jekyll (>= 2.0)
listen (~> 3.0, < 3.1) jekyll-sitemap (0.9.0)
jekyll-watch (1.5.1)
listen (~> 3.0)
jemoji (0.5.0) jemoji (0.5.0)
gemoji (~> 2.0) gemoji (~> 2.0)
html-pipeline (~> 1.9) html-pipeline (~> 1.9)
jekyll (>= 2.0) jekyll (>= 2.0)
kramdown (1.5.0) kramdown (1.9.0)
liquid (2.6.2) liquid (2.6.2)
listen (3.0.8) listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4) rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7) rb-inotify (~> 0.9, >= 0.9.7)
ruby_dep (~> 1.2)
maruku (0.7.0) maruku (0.7.0)
mercenary (0.3.6) mercenary (0.3.6)
mini_portile2 (2.1.0) mini_portile2 (2.3.0)
minitest (5.9.1) minitest (5.11.3)
multipart-post (2.0.0) multipart-post (2.0.0)
net-dns (0.8.0) net-dns (0.8.0)
nokogiri (1.6.8.1) nokogiri (1.8.3)
mini_portile2 (~> 2.1.0) mini_portile2 (~> 2.3.0)
nokogiri (1.6.8.1-x64-mingw32) octokit (4.9.0)
mini_portile2 (~> 2.1.0)
octokit (4.6.1)
sawyer (~> 0.8.0, >= 0.5.3) sawyer (~> 0.8.0, >= 0.5.3)
parslet (1.5.0) parslet (1.5.0)
blankslate (~> 2.0) blankslate (~> 2.0)
posix-spawn (0.3.12) posix-spawn (0.3.13)
public_suffix (1.5.3) public_suffix (1.5.3)
pygments.rb (0.6.3) pygments.rb (0.6.3)
posix-spawn (~> 0.3.6) posix-spawn (~> 0.3.6)
yajl-ruby (~> 1.2.0) yajl-ruby (~> 1.2.0)
rb-fsevent (0.9.8) rb-fsevent (0.10.3)
rb-inotify (0.9.7) rb-inotify (0.9.10)
ffi (>= 0.5.0) ffi (>= 0.5.0, < 2)
rdiscount (2.1.7) rdiscount (2.1.8)
redcarpet (3.3.2) redcarpet (3.3.3)
rouge (2.0.7) rouge (3.1.1)
ruby_dep (1.5.0)
safe_yaml (1.0.4) safe_yaml (1.0.4)
sass (3.4.22) sass (3.5.6)
sass-listen (~> 4.0.0)
sass-listen (4.0.0)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
sawyer (0.8.1) sawyer (0.8.1)
addressable (>= 2.3.5, < 2.6) addressable (>= 2.3.5, < 2.6)
faraday (~> 0.8, < 1.0) faraday (~> 0.8, < 1.0)
terminal-table (1.7.3) terminal-table (1.8.0)
unicode-display_width (~> 1.1.1) unicode-display_width (~> 1.1, >= 1.1.1)
thread_safe (0.3.5) thread_safe (0.3.6)
toml (0.1.2) toml (0.1.2)
parslet (~> 1.5.0) parslet (~> 1.5.0)
typhoeus (0.8.0) typhoeus (0.8.0)
ethon (>= 0.8.0) ethon (>= 0.8.0)
tzinfo (1.2.2) tzinfo (1.2.5)
thread_safe (~> 0.1) thread_safe (~> 0.1)
unicode-display_width (1.1.1) unicode-display_width (1.4.0)
yajl-ruby (1.2.1) yajl-ruby (1.2.3)
PLATFORMS PLATFORMS
ruby ruby
x64-mingw32
DEPENDENCIES DEPENDENCIES
github-pages github-pages
rouge rouge
BUNDLED WITH BUNDLED WITH
1.13.6 1.16.2

View File

@@ -36,27 +36,27 @@ You should read the `CONTRIBUTING.md` file for precise instructions and tips. Bu
<http://www.phptherightway.com> <http://www.phptherightway.com>
* [English](http://www.phptherightway.com) * [English](http://www.phptherightway.com)
* [Bulgarian](http://bg.phptherightway.com) * [Deutsch](http://rwetzlmayr.github.io/php-the-right-way)
* [Chinese (Simplified)](http://laravel-china.github.io/php-the-right-way/) * [Español](http://phpdevenezuela.github.io/php-the-right-way)
* [Chinese (Traditional)](http://laravel-taiwan.github.io/php-the-right-way) * [Français](http://eilgin.github.io/php-the-right-way/)
* [French](http://eilgin.github.io/php-the-right-way/) * [Indonesia](http://id.phptherightway.com)
* [German](http://rwetzlmayr.github.io/php-the-right-way) * [Italiano](http://it.phptherightway.com)
* [Indonesian](http://id.phptherightway.com) * [Polski](http://pl.phptherightway.com)
* [Italian](http://it.phptherightway.com) * [Português do Brasil](http://br.phptherightway.com)
* [Japanese](http://ja.phptherightway.com) * [Română](https://bgui.github.io/php-the-right-way/)
* [Korean](http://modernpug.github.io/php-the-right-way) * [Slovenščina](http://sl.phptherightway.com)
* [Persian](http://novid.github.io/php-the-right-way/) * [Srpski](http://phpsrbija.github.io/php-the-right-way/)
* [Polish](http://pl.phptherightway.com) * [Türkçe](http://hkulekci.github.io/php-the-right-way/)
* [Portuguese (Brazil)](http://br.phptherightway.com) * [български](http://bg.phptherightway.com)
* [Romanian](https://bgui.github.io/php-the-right-way/) * [Русский язык](http://getjump.github.io/ru-php-the-right-way)
* [Russian](http://getjump.github.io/ru-php-the-right-way) * [Українська](http://iflista.github.com/php-the-right-way)
* [Serbian](http://phpsrbija.github.io/php-the-right-way/)
* [Slovenian](http://sl.phptherightway.com)
* [Spanish](http://phpdevenezuela.github.io/php-the-right-way)
* [Thai](https://apzentral.github.io/php-the-right-way/)
* [Turkish](http://hkulekci.github.io/php-the-right-way/)
* [Ukrainian](http://iflista.github.com/php-the-right-way)
* [العربية](https://adaroobi.github.io/php-the-right-way/) * [العربية](https://adaroobi.github.io/php-the-right-way/)
* [فارسى](http://novid.github.io/php-the-right-way/)
* [ภาษาไทย](https://apzentral.github.io/php-the-right-way/)
* [한국어판](http://modernpug.github.io/php-the-right-way)
* [日本語](http://ja.phptherightway.com)
* [简体中文](http://laravel-china.github.io/php-the-right-way/)
* [繁體中文](http://laravel-taiwan.github.io/php-the-right-way)
### Translations ### Translations

View File

@@ -21,27 +21,27 @@ and examples as they become available.
_PHP: The Right Way_ is translated into many different languages: _PHP: The Right Way_ is translated into many different languages:
* [English](http://www.phptherightway.com) * [English](http://www.phptherightway.com)
* [Bulgarian](http://bg.phptherightway.com/) * [Deutsch](http://rwetzlmayr.github.io/php-the-right-way)
* [Chinese (Simplified)](http://laravel-china.github.io/php-the-right-way/) * [Español](http://phpdevenezuela.github.io/php-the-right-way)
* [Chinese (Traditional)](http://laravel-taiwan.github.io/php-the-right-way) * [Français](http://eilgin.github.io/php-the-right-way/)
* [French](http://eilgin.github.io/php-the-right-way/) * [Indonesia](http://id.phptherightway.com)
* [German](http://rwetzlmayr.github.io/php-the-right-way/) * [Italiano](http://it.phptherightway.com)
* [Indonesian](http://id.phptherightway.com/) * [Polski](http://pl.phptherightway.com)
* [Italian](http://it.phptherightway.com/) * [Português do Brasil](http://br.phptherightway.com)
* [Japanese](http://ja.phptherightway.com) * [Română](https://bgui.github.io/php-the-right-way/)
* [Korean](http://modernpug.github.io/php-the-right-way/) * [Slovenščina](http://sl.phptherightway.com)
* [Persian](http://novid.github.io/php-the-right-way/) * [Srpski](http://phpsrbija.github.io/php-the-right-way/)
* [Polish](http://pl.phptherightway.com/) * [Türkçe](http://hkulekci.github.io/php-the-right-way/)
* [Portuguese (Brazil)](http://br.phptherightway.com/) * [български](http://bg.phptherightway.com)
* [Romanian](https://bgui.github.io/php-the-right-way/) * [Русский язык](http://getjump.github.io/ru-php-the-right-way)
* [Russian](http://getjump.github.io/ru-php-the-right-way) * [Українська](http://iflista.github.com/php-the-right-way)
* [Serbian](http://phpsrbija.github.io/php-the-right-way/)
* [Slovenian](http://sl.phptherightway.com)
* [Spanish](http://phpdevenezuela.github.io/php-the-right-way/)
* [Thai](https://apzentral.github.io/php-the-right-way/)
* [Turkish](http://hkulekci.github.io/php-the-right-way/)
* [Ukrainian](http://iflista.github.com/php-the-right-way/)
* [العربية](https://adaroobi.github.io/php-the-right-way/) * [العربية](https://adaroobi.github.io/php-the-right-way/)
* [فارسى](http://novid.github.io/php-the-right-way/)
* [ภาษาไทย](https://apzentral.github.io/php-the-right-way/)
* [한국어판](http://modernpug.github.io/php-the-right-way)
* [日本語](http://ja.phptherightway.com)
* [简体中文](http://laravel-china.github.io/php-the-right-way/)
* [繁體中文](http://laravel-taiwan.github.io/php-the-right-way)
## Book ## Book
@@ -51,13 +51,5 @@ The most recent version of _PHP: The Right Way_ is also available in PDF, EPUB a
Help make this website the best resource for new PHP programmers! [Contribute on GitHub][2] Help make this website the best resource for new PHP programmers! [Contribute on GitHub][2]
## Spread the Word!
_PHP: The Right Way_ has web banner images you can use on your website. Show your support, and let new PHP developers
know where to find good information!
[See Banner Images][3]
[1]: https://leanpub.com/phptherightway [1]: https://leanpub.com/phptherightway
[2]: https://github.com/codeguy/php-the-right-way/tree/gh-pages [2]: https://github.com/codeguy/php-the-right-way/tree/gh-pages
[3]: /banners.html

View File

@@ -5,12 +5,12 @@
<title>{% if page.title %}{{ page.title }} - {% endif %}PHP: The Right Way</title> <title>{% if page.title %}{{ page.title }} - {% endif %}PHP: The Right Way</title>
<meta name="description" content="{{ page.description }}"/> <meta name="description" content="{{ page.description }}"/>
<meta name="robots" content="index,follow,archive"/> <meta name="robots" content="index,follow,archive"/>
<meta property="og:image:url" content="http://www.phptherightway.com/images/og-image.png"/> <meta property="og:image:url" content="https://www.phptherightway.com/images/og-image.png"/>
<meta property="og:image:width" content="1024"/> <meta property="og:image:width" content="1024"/>
<meta property="og:image:height" content="640"/> <meta property="og:image:height" content="640"/>
<meta property="og:title" content="PHP: The Right Way"/> <meta property="og:title" content="PHP: The Right Way"/>
<meta property="og:description" content="An easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative PHP tutorials around the Web"/> <meta property="og:description" content="An easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative PHP tutorials around the Web"/>
<meta property="og:url" content="http://www.phptherightway.com"/> <meta property="og:url" content="https://www.phptherightway.com"/>
<meta property="og:site_name" content="PHP: The Right Way"/> <meta property="og:site_name" content="PHP: The Right Way"/>
<meta property="og:type" content="website"/> <meta property="og:type" content="website"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
@@ -25,7 +25,7 @@
<h1><a href="/">PHP <em>The Right Way</em></a></h1> <h1><a href="/">PHP <em>The Right Way</em></a></h1>
<div class="build-date">Last Updated: {{ site.time }}</div> <div class="build-date">Last Updated: {{ site.time }}</div>
<div class="share"> <div class="share">
<a class="btn-share" href="https://twitter.com/intent/tweet?text=PHP+The+Right+Way&amp;url=http%3A%2F%2Fwww.phptherightway.com&amp;hashtags=PHP" target="_blank">Share on Twitter</a> <a class="btn-share" href="https://twitter.com/intent/tweet?text=PHP+The+Right+Way&amp;url=https%3A%2F%2Fwww.phptherightway.com&amp;hashtags=PHP" target="_blank">Share on Twitter</a>
</div> </div>
<a class="fork-me" href="https://github.com/codeguy/php-the-right-way" target="_blank"></a> <a class="fork-me" href="https://github.com/codeguy/php-the-right-way" target="_blank"></a>
</header> </header>
@@ -72,27 +72,17 @@
<footer class="site-footer" id="credits"> <footer class="site-footer" id="credits">
<h2>Created and maintained by</h2> <h2>Created and maintained by</h2>
<ul> <ul>
<li><a href="http://joshlockhart.com" target="_blank">Josh Lockhart</a></li> <li><a href="https://joshlockhart.com" target="_blank">Josh Lockhart</a></li>
<li><a href="http://philsturgeon.co.uk/" target="_blank">Phil Sturgeon</a></li> <li><a href="https://philsturgeon.uk/" target="_blank">Phil Sturgeon</a></li>
<li><a href="https://github.com/codeguy/php-the-right-way/graphs/contributors" target="_blank">Project Contributors</a></li> <li><a href="https://github.com/codeguy/php-the-right-way/graphs/contributors" target="_blank">Project Contributors</a></li>
</ul> </ul>
<div class="license"> <div class="license">
<a class="cc-badge" rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/"></a> <a class="cc-badge" rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/"></a>
<br /> <br />
<span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">PHP: The Right Way</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="http://joshlockhart.com" property="cc:attributionName" rel="cc:attributionURL">Josh Lockhart</a> <span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">PHP: The Right Way</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://joshlockhart.com" property="cc:attributionName" rel="cc:attributionURL">Josh Lockhart</a>
<br/> <br/>
is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="http://www.phptherightway.com" rel="dct:source">www.phptherightway.com</a>. is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://www.phptherightway.com" rel="dct:source">www.phptherightway.com</a>.
</div> </div>
</footer> </footer>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-362072-7']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body> </body>
</html> </html>

View File

@@ -5,12 +5,12 @@
<title>{% if page.title %}{{ page.title }} - {% endif %}PHP: The Right Way</title> <title>{% if page.title %}{{ page.title }} - {% endif %}PHP: The Right Way</title>
<meta name="description" content="{{ page.description }}"/> <meta name="description" content="{{ page.description }}"/>
<meta name="robots" content="index,follow,archive"/> <meta name="robots" content="index,follow,archive"/>
<meta property="og:image:url" content="http://www.phptherightway.com/images/og-image.png"/> <meta property="og:image:url" content="https://www.phptherightway.com/images/og-image.png"/>
<meta property="og:image:width" content="1024"/> <meta property="og:image:width" content="1024"/>
<meta property="og:image:height" content="640"/> <meta property="og:image:height" content="640"/>
<meta property="og:title" content="PHP: The Right Way"/> <meta property="og:title" content="PHP: The Right Way"/>
<meta property="og:description" content="An easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative PHP tutorials around the Web"/> <meta property="og:description" content="An easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative PHP tutorials around the Web"/>
<meta property="og:url" content="http://www.phptherightway.com"/> <meta property="og:url" content="https://www.phptherightway.com"/>
<meta property="og:site_name" content="PHP: The Right Way"/> <meta property="og:site_name" content="PHP: The Right Way"/>
<meta property="og:type" content="website"/> <meta property="og:type" content="website"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
@@ -25,7 +25,7 @@
<h1><a href="/">PHP <em>The Right Way</em></a></h1> <h1><a href="/">PHP <em>The Right Way</em></a></h1>
<div class="build-date">Last Updated: {{ site.time }}</div> <div class="build-date">Last Updated: {{ site.time }}</div>
<div class="share"> <div class="share">
<a class="btn-share" href="https://twitter.com/intent/tweet?text=PHP+The+Right+Way&amp;url=http%3A%2F%2Fwww.phptherightway.com&amp;hashtags=PHP" target="_blank">Share on Twitter</a> <a class="btn-share" href="https://twitter.com/intent/tweet?text=PHP+The+Right+Way&amp;url=https%3A%2F%2Fwww.phptherightway.com&amp;hashtags=PHP" target="_blank">Share on Twitter</a>
</div> </div>
<a class="fork-me" href="https://github.com/codeguy/php-the-right-way" target="_blank"></a> <a class="fork-me" href="https://github.com/codeguy/php-the-right-way" target="_blank"></a>
</header> </header>
@@ -37,27 +37,17 @@
<footer class="site-footer" id="credits"> <footer class="site-footer" id="credits">
<h2>Created and maintained by</h2> <h2>Created and maintained by</h2>
<ul> <ul>
<li><a href="http://joshlockhart.com" target="_blank">Josh Lockhart</a></li> <li><a href="https://joshlockhart.com" target="_blank">Josh Lockhart</a></li>
<li><a href="http://philsturgeon.co.uk/" target="_blank">Phil Sturgeon</a></li> <li><a href="https://philsturgeon.co.uk/" target="_blank">Phil Sturgeon</a></li>
<li><a href="https://github.com/codeguy/php-the-right-way/graphs/contributors" target="_blank">Project Contributors</a></li> <li><a href="https://github.com/codeguy/php-the-right-way/graphs/contributors" target="_blank">Project Contributors</a></li>
</ul> </ul>
<div class="license"> <div class="license">
<a class="cc-badge" rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/"></a> <a class="cc-badge" rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/"></a>
<br /> <br />
<span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">PHP: The Right Way</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="http://joshlockhart.com" property="cc:attributionName" rel="cc:attributionURL">Josh Lockhart</a> <span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">PHP: The Right Way</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://joshlockhart.com" property="cc:attributionName" rel="cc:attributionURL">Josh Lockhart</a>
<br/> <br/>
is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="http://www.phptherightway.com" rel="dct:source">www.phptherightway.com</a>. is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://www.phptherightway.com" rel="dct:source">www.phptherightway.com</a>.
</div> </div>
</footer> </footer>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-362072-7']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body> </body>
</html> </html>

View File

@@ -1,16 +1,15 @@
--- ---
title: Use the Current Stable Version (7.0) title: Use the Current Stable Version (7.2)
isChild: true isChild: true
anchor: use_the_current_stable_version anchor: use_the_current_stable_version
--- ---
## Use the Current Stable Version (7.0) {#use_the_current_stable_version_title} ## Use the Current Stable Version (7.2) {#use_the_current_stable_version_title}
If you are getting started with PHP, start with the current stable release of [PHP 7.0][php-release]. PHP 7.0 is very If you are getting started with PHP, start with the current stable release of [PHP 7.2][php-release]. PHP 7.x adds many [new features](#language_highlights) over the older 5.x versions. The engine has been largely re-written, and PHP is now even quicker than older versions.
new, and adds many amazing [new features](#language_highlights) over the older 5.x versions. The engine has been largely re-written, and PHP is now even quicker than older versions.
Most commonly in the near future you will find PHP 5.x being used, and the latest 5.x version is 5.6. This is not a bad option, but you should try to upgrade to the latest stable quickly - PHP 5.6 [will not receive security updates beyond 2018](http://php.net/supported-versions.php). Upgrading is really quite easy, as there are not many [backwards compatibility breaks][php70-bc]. If you are not sure which version a function or feature is in, you can check the PHP documentation on the [php.net][php-docs] website. You should try to upgrade to the latest stable version quickly - PHP 5.6 [will not receive security updates beyond 2018](http://php.net/supported-versions.php). Upgrading is easy, as there are not many [backwards compatibility breaks][php72-bc]. If you are not sure which version a function or feature is in, you can check the PHP documentation on the [php.net][php-docs] website.
[php-release]: http://php.net/downloads.php [php-release]: http://php.net/downloads.php
[php-docs]: http://php.net/manual/ [php-docs]: http://php.net/manual/
[php70-bc]: http://php.net/manual/migration70.incompatible.php [php72-bc]: http://php.net/manual/migration72.incompatible.php

View File

@@ -5,18 +5,17 @@ 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. Mavericks has 5.4.17, macOS comes prepackaged with PHP but it is normally a little behind the latest stable release. There are multiple ways to install the latest PHP version on macOS.
Yosemite 5.5.9, El Capitan 5.5.29 and Sierra 5.6.24, but with PHP 7.0 out that is often not good enough.
There are multiple ways to install PHP on OS X.
### Install PHP via Homebrew ### Install PHP via Homebrew
[Homebrew] is a powerful package manager for OS X, which can help you install PHP and various extensions easily. [Homebrew] is a package manager for macOS that helps you easily install PHP and various extensions. The Homebrew core repository provides "formulae" for PHP 5.6, 7.0, 7.1, and 7.2. Install the latest version with this command:
[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`, `php56` or `php70` using the `brew install` command, and switch ```
between them by modifying your `PATH` variable. Alternatively you can use [brew-php-switcher][brew-php-switcher] which will switch automatically for you. brew install php@7.2
```
You can switch between Homebrew PHP versions by modifying your `PATH` variable. Alternatively, you can use [brew-php-switcher][brew-php-switcher] to switch PHP versions automatically.
### Install PHP via Macports ### Install PHP via Macports
@@ -29,14 +28,14 @@ MacPorts supports pre-compiled binaries, so you don't need to recompile every
dependency from the source tarball files, it saves your life if you don't dependency from the source tarball files, it saves your life if you don't
have any package installed on your system. have any package installed on your system.
At this point, you can install `php54`, `php55`, `php56` or `php70` using the `port install` command, for example: At this point, you can install `php54`, `php55`, `php56`, `php70` or `php71` using the `port install` command, for example:
sudo port install php56 sudo port install php56
sudo port install php70 sudo port install php71
And you can run `select` command to switch your active PHP: And you can run `select` command to switch your active PHP:
sudo port select --set php php70 sudo port select --set php php71
### Install PHP via phpbrew ### Install PHP via phpbrew
@@ -45,7 +44,7 @@ applications/projects require different versions of PHP, and you are not using v
### Install PHP via Liip's binary installer ### Install PHP via Liip's binary installer
Another popular option is [php-osx.liip.ch] which provides one liner installation methods for versions 5.3 through 7.0. Another popular option is [php-osx.liip.ch] which provides one liner installation methods for versions 5.3 through 7.1.
It doesn't overwrite the PHP binaries installed by Apple, but installs everything in a separate location (/usr/local/php5). It doesn't overwrite the PHP binaries installed by Apple, but installs everything in a separate location (/usr/local/php5).
### Compile from Source ### Compile from Source
@@ -60,15 +59,14 @@ The solutions listed above mainly handle PHP itself, and do not supply things li
"All-in-one" solutions such as [MAMP][mamp-downloads] and [XAMPP][xampp] will install these other bits of software for "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. you and tie them all together, but ease of setup comes with a trade-off of flexibility.
[Homebrew]: https://brew.sh/
[Homebrew]: http://brew.sh/
[Homebrew PHP]: https://github.com/Homebrew/homebrew-php#installation [Homebrew PHP]: https://github.com/Homebrew/homebrew-php#installation
[MacPorts]: https://www.macports.org/install.php [MacPorts]: https://www.macports.org/install.php
[phpbrew]: https://github.com/phpbrew/phpbrew [phpbrew]: https://github.com/phpbrew/phpbrew
[php-osx.liip.ch]: http://php-osx.liip.ch/ [php-osx.liip.ch]: https://php-osx.liip.ch/
[mac-compile]: http://php.net/install.macosx.compile [mac-compile]: https://secure.php.net/install.macosx.compile
[xcode-gcc-substitution]: https://github.com/kennethreitz/osx-gcc-installer [xcode-gcc-substitution]: https://github.com/kennethreitz/osx-gcc-installer
["Command Line Tools for XCode"]: https://developer.apple.com/downloads ["Command Line Tools for XCode"]: https://developer.apple.com/downloads
[mamp-downloads]: http://www.mamp.info/en/downloads/ [mamp-downloads]: https://www.mamp.info/en/downloads/
[xampp]: http://www.apachefriends.org/en/xampp.html [xampp]: https://www.apachefriends.org/index.html
[brew-php-switcher]: https://github.com/philcook/brew-php-switcher [brew-php-switcher]: https://github.com/philcook/brew-php-switcher

View File

@@ -1,22 +1,22 @@
--- ---
isChild: true isChild: true
anchor: windows_setup anchor: windows_setup
--- ---
## Windows Setup {#windows_setup_title} ## Windows Setup {#windows_setup_title}
You can download the binaries from [windows.php.net/download][php-downloads]. After the extraction of PHP, it is recommended to set the [PATH][windows-path] to the root of your PHP folder (where php.exe is located) so you can execute PHP from anywhere. You can download the binaries from [windows.php.net/download][php-downloads]. After the extraction of PHP, it is recommended to set the [PATH][windows-path] to the root of your PHP folder (where php.exe is located) so you can execute PHP from anywhere.
For learning and local development, you can use the built in webserver with PHP 5.4+ so you don't need to worry about 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 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], [XAMPP][xampp], [EasyPHP][easyphp], [OpenServer][openserver] and [WAMP][wamp] will as the [Web Platform Installer][wpi], [XAMPP][xampp], [EasyPHP][easyphp], [OpenServer][openserver] and [WAMP][wamp] will
help get a Windows development environment up and running fast. That said, these tools will be a little different from 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. 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 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 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 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. there is a [dedicated area on iis.net][php-iis] for PHP.
Generally running your application on different environment in development and production can lead to strange bugs popping up when you go Generally running your application on different environment in development and production can lead to strange bugs popping up when you go
live. If you are developing on Windows and deploying to Linux (or anything non-Windows) then you should consider using a [Virtual Machine](/#virtualization_title). live. If you are developing on Windows and deploying to Linux (or anything non-Windows) then you should consider using a [Virtual Machine](/#virtualization_title).
@@ -31,5 +31,5 @@ Chris Tankersley has a very helpful blog post on what tools he uses to do [PHP d
[php-iis]: http://php.iis.net/ [php-iis]: http://php.iis.net/
[windows-path]: http://www.windows-commandline.com/set-path-command-line/ [windows-path]: http://www.windows-commandline.com/set-path-command-line/
[windows-tools]: http://ctankersley.com/2016/11/13/developing-on-windows-2016/ [windows-tools]: http://ctankersley.com/2016/11/13/developing-on-windows-2016/
[wpi]: http://www.microsoft.com/web/downloads/platform.aspx [wpi]: https://www.microsoft.com/web/downloads/platform.aspx
[xampp]: http://www.apachefriends.org/en/xampp.html [xampp]: http://www.apachefriends.org/en/xampp.html

View File

@@ -0,0 +1,19 @@
---
title: Common Directory Structure
isChild: true
anchor: common_directory_structure
---
## Common Directory structure {#common_directory_structure_title}
A common question among those starting out with writing programs for the web is, "where do I put my stuff?" Over the years, this answer has consistently been "where the `DocumentRoot` is." Although this answer is not complete, it's a great place to start.
For security reasons, configuration files should not be accessible by a site's visitors; therefore, public scripts are kept in a public directory and private configurations and data are kept outside of that directory.
For each team, CMS, or framework one works in, a standard directory structure is used by each of those entities. However, if one is starting a project alone, knowing which filesystem structure to use can be daunting.
[Paul M. Jones] has done some fantastic research into common practices of tens of thousands of github projects in the realm of PHP. He has compiled a standard file and directory structure, the [Standard PHP Package Skeleton], based on this research. In this directory structure, `DocumentRoot` should point to `public/`, unit tests should be in the `tests/` directory, and third party libraries, as installed by [composer], belong in the `vendor/` directory. For other files and directories, abiding by the [Standard PHP Package Skeleton] will make the most sense to contributors of a project.
[Paul M. Jones]: https://twitter.com/pmjones
[Standard PHP Package Skeleton]: https://github.com/php-pds/skeleton
[Composer]: /#composer_and_packagist

View File

@@ -10,16 +10,15 @@ PHP developers to choose several of these and combine them into a single project
their projects. their projects.
The [Framework Interop Group][fig] has proposed and approved a series of style recommendations. Not all of them related The [Framework Interop Group][fig] has proposed and approved a series of style recommendations. Not all of them related
to code-style, but those that do are [PSR-0][psr0], [PSR-1][psr1], [PSR-2][psr2] and [PSR-4][psr4]. These to code-style, but those that do are [PSR-1][psr1], [PSR-2][psr2] and [PSR-4][psr4]. These
recommendations are merely a set of rules that many projects like Drupal, Zend, Symfony, Laravel, CakePHP, phpBB, AWS SDK, recommendations are merely a set of rules that many projects like Drupal, Zend, Symfony, Laravel, CakePHP, phpBB, AWS SDK,
FuelPHP, Lithium, etc are adopting. You can use them for your own projects, or continue to use your own FuelPHP, Lithium, etc are adopting. You can use them for your own projects, or continue to use your own
personal style. personal style.
Ideally you should write PHP code that adheres to a known standard. This could be any combination of PSRs, or one Ideally, you should write PHP code that adheres to a known standard. This could be any combination of PSRs, or one
of the coding standards made by PEAR or Zend. This means other developers can easily read and work with your code, and 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. 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] * [Read about PSR-1][psr1]
* [Read about PSR-2][psr2] * [Read about PSR-2][psr2]
* [Read about PSR-4][psr4] * [Read about PSR-4][psr4]
@@ -56,15 +55,16 @@ It will show which kind of errors the code structure had before it fixed them.
English is preferred for all symbol names and code infrastructure. Comments may be written in any language easily 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. readable by all current and future parties who may be working on the codebase.
Finally, a good supplementary resource for writing clean PHP code is [Clean Code PHP][cleancode].
[fig]: http://www.php-fig.org/ [fig]: https://www.php-fig.org/
[psr0]: http://www.php-fig.org/psr/psr-0/ [psr1]: https://www.php-fig.org/psr/psr-1/
[psr1]: http://www.php-fig.org/psr/psr-1/ [psr2]: https://www.php-fig.org/psr/psr-2/
[psr2]: http://www.php-fig.org/psr/psr-2/ [psr4]: https://www.php-fig.org/psr/psr-4/
[psr4]: http://www.php-fig.org/psr/psr-4/ [pear-cs]: https://pear.php.net/manual/en/standards.php
[pear-cs]: http://pear.php.net/manual/en/standards.php [symfony-cs]: https://symfony.com/doc/current/contributing/code/standards.html
[symfony-cs]: http://symfony.com/doc/current/contributing/code/standards.html [phpcs]: https://pear.php.net/package/PHP_CodeSniffer/
[phpcs]: http://pear.php.net/package/PHP_CodeSniffer/
[phpcbf]: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Fixing-Errors-Automatically [phpcbf]: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Fixing-Errors-Automatically
[st-cs]: https://github.com/benmatselby/sublime-phpcs [st-cs]: https://github.com/benmatselby/sublime-phpcs
[phpcsfixer]: http://cs.sensiolabs.org/ [phpcsfixer]: https://cs.sensiolabs.org/
[cleancode]: https://github.com/jupeter/clean-code-php

View File

@@ -50,14 +50,14 @@ available as `__call()` and `__callStatic()`.
* [Read about Overloading][overloading] * [Read about Overloading][overloading]
[oop]: http://php.net/language.oop5 [oop]: https://secure.php.net/language.oop5
[traits]: http://php.net/language.oop5.traits [traits]: https://secure.php.net/language.oop5.traits
[anonymous-functions]: http://php.net/functions.anonymous [anonymous-functions]: https://secure.php.net/functions.anonymous
[closure-class]: http://php.net/class.closure [closure-class]: https://secure.php.net/class.closure
[closures-rfc]: https://wiki.php.net/rfc/closures [closures-rfc]: https://wiki.php.net/rfc/closures
[callables]: http://php.net/language.types.callable [callables]: https://secure.php.net/language.types.callable
[call-user-func-array]: http://php.net/function.call-user-func-array [call-user-func-array]: https://secure.php.net/function.call-user-func-array
[magic-methods]: http://php.net/language.oop5.magic [magic-methods]: https://secure.php.net/language.oop5.magic
[reflection]: http://php.net/intro.reflection [reflection]: https://secure.php.net/intro.reflection
[overloading]: http://php.net/language.oop5.overloading [overloading]: https://secure.php.net/language.oop5.overloading

View File

@@ -28,6 +28,6 @@ If you're going to use an autoloader standard for a new application or package,
* [Read about PSR-4][psr4] * [Read about PSR-4][psr4]
[namespaces]: http://php.net/language.namespaces [namespaces]: https://secure.php.net/language.namespaces
[psr0]: http://www.php-fig.org/psr/psr-0/ [psr0]: https://www.php-fig.org/psr/psr-0/
[psr4]: http://www.php-fig.org/psr/psr-4/ [psr4]: https://www.php-fig.org/psr/psr-4/

View File

@@ -14,5 +14,5 @@ over these datastructures or your own classes which implement SPL interfaces.
* [SPL video course on Lynda.com(Paid)][spllynda] * [SPL video course on Lynda.com(Paid)][spllynda]
[spl]: http://php.net/book.spl [spl]: https://secure.php.net/book.spl
[spllynda]: http://www.lynda.com/PHP-tutorials/Up-Running-Standard-PHP-Library/175038-2.html [spllynda]: https://www.lynda.com/PHP-tutorials/Up-Running-Standard-PHP-Library/175038-2.html

View File

@@ -52,13 +52,10 @@ Hello, world
* [Learn about running PHP from the command line][php-cli] * [Learn about running PHP from the command line][php-cli]
* [Learn about setting up Windows to run PHP from the command line][php-cli-windows]
[phpinfo]: https://secure.php.net/function.phpinfo
[phpinfo]: http://php.net/function.phpinfo [cli-options]: https://secure.php.net/features.commandline.options
[cli-options]: http://php.net/features.commandline.options [argc]: https://secure.php.net/reserved.variables.argc
[argc]: http://php.net/reserved.variables.argc [argv]: https://secure.php.net/reserved.variables.argv
[argv]: http://php.net/reserved.variables.argv [exit-codes]: https://www.gsp.com/cgi-bin/man.cgi?section=3&amp;topic=sysexits
[exit-codes]: http://www.gsp.com/cgi-bin/man.cgi?section=3&amp;topic=sysexits [php-cli]: https://secure.php.net/features.commandline.options
[php-cli]: http://php.net/features.commandline
[php-cli-windows]: http://php.net/install.windows.commandline

View File

@@ -41,6 +41,6 @@ stand-alone Xdebug GUI for Mac.
* [Learn more about MacGDBp][macgdbp-install] * [Learn more about MacGDBp][macgdbp-install]
[xdebug-install]: http://xdebug.org/docs/install [xdebug-install]: https://xdebug.org/docs/install
[xdebug-docs]: http://xdebug.org/docs/ [xdebug-docs]: https://xdebug.org/docs/
[macgdbp-install]: http://www.bluestatic.org/software/macgdbp/ [macgdbp-install]: https://www.bluestatic.org/software/macgdbp/

View File

@@ -6,20 +6,20 @@ anchor: composer_and_packagist
## Composer and Packagist {#composer_and_packagist_title} ## Composer and Packagist {#composer_and_packagist_title}
Composer is a **brilliant** dependency manager for PHP. List your project's dependencies in a `composer.json` file and, Composer is the recommended 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 with a few simple commands, Composer will automatically download your project's dependencies and setup autoloading for
you. Composer is analogous to NPM in the node.js world, or Bundler in the Ruby world. you. Composer is analogous to NPM in the node.js world, or Bundler in the Ruby world.
There are already a lot of PHP libraries that are compatible with Composer, ready to be used in your project. These There is a plethora of PHP libraries that are compatible with Composer and ready to be used in your project. These
"packages" are listed on [Packagist], the official repository for Composer-compatible PHP libraries. "packages" are listed on [Packagist], the official repository for Composer-compatible PHP libraries.
### How to Install Composer ### How to Install Composer
The safest way to download composer is by [following the official instructions](https://getcomposer.org/download/). The safest way to download composer is by [following the official instructions](https://getcomposer.org/download/).
This will verify the installer is not corrupt or tampered with. This will verify the installer is not corrupt or tampered with.
The installer installs Composer *locally*, in your current working directory. The installer installs a `composer.phar` binary in your _current working directory_.
We recommend installing it *globally* (e.g. a single copy in /usr/local/bin) - to do so, run this afterwards: We recommend installing Composer *globally* (e.g. a single copy in `/usr/local/bin`). To do so, run this command next:
{% highlight console %} {% highlight console %}
mv composer.phar /usr/local/bin/composer mv composer.phar /usr/local/bin/composer
@@ -35,59 +35,27 @@ For Windows users the easiest way to get up and running is to use the [ComposerS
performs a global install and sets up your `$PATH` so that you can just call `composer` from any performs a global install and sets up your `$PATH` so that you can just call `composer` from any
directory in your command line. 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:
- a sufficient version of PHP is being used
- `.phar` files can be executed correctly
- certain directory permissions are sufficient
- 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:
{% 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.
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 %}
This section will assume you have installed composer globally.
### How to Define and Install Dependencies ### How to Define and Install Dependencies
Composer keeps track of your project's dependencies in a file called `composer.json`. You can manage it 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 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] and if you don't have a `composer.json` file, one will be created. Here's an example that adds [Twig]
as a dependency of your project. as a dependency of your project.
{% highlight console %} {% highlight console %}
composer require twig/twig:~1.8 composer require twig/twig:^2.0
{% endhighlight %} {% endhighlight %}
Alternatively, the `composer init` command will guide you through creating a full `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 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 download and install your dependencies into the `vendor/` directory. This also applies to projects
you've downloaded that already provide a `composer.json` file: you've downloaded that already provide a `composer.json` file:
{% highlight console %} {% highlight console %}
composer install composer install
{% endhighlight %} {% endhighlight %}
Next, add this line to your application's primary PHP file; this will tell PHP to use Composer's Next, add this line to your application's primary PHP file; this will tell PHP to use Composer's
autoloader for your project dependencies. autoloader for your project dependencies.
{% highlight php %} {% highlight php %}
@@ -100,14 +68,14 @@ Now you can use your project dependencies, and they'll be autoloaded on demand.
### Updating your dependencies ### Updating your dependencies
Composer creates a file called `composer.lock` which stores the exact version of each package it Composer creates a file called `composer.lock` which stores the exact version of each package it
downloaded when you first ran `composer install`. If you share your project with others, downloaded when you first ran `composer install`. If you share your project with others,
ensure the `composer.lock` file is included, so that when they run `composer install` they'll ensure the `composer.lock` file is included, so that when they run `composer install` they'll
get the same versions as you. To update your dependencies, run `composer update`. Don't use get the same versions as you. To update your dependencies, run `composer update`. Don't use
`composer update` when deploying, only `composer install`, otherwise you may end up with different `composer update` when deploying, only `composer install`, otherwise you may end up with different
package versions on production. package versions on production.
This is most useful when you define your version requirements flexibly. For instance, a version This is most useful when you define your version requirements flexibly. For instance, a version
requirement of `~1.8` means "anything newer than `1.8.0`, but less than `2.0.x-dev`". You can also use requirement of `~1.8` means "anything newer than `1.8.0`, but less than `2.0.x-dev`". You can also use
the `*` wildcard as in `1.8.*`. Now Composer's `composer update` command will upgrade all your the `*` wildcard as in `1.8.*`. Now Composer's `composer update` command will upgrade all your
dependencies to the newest version that fits the restrictions you define. dependencies to the newest version that fits the restrictions you define.
@@ -125,7 +93,7 @@ file and tell you if you need to update any of your dependencies.
### Handling global dependencies with Composer ### Handling global dependencies with Composer
Composer can also handle global dependencies and their binaries. Usage is straight-forward, all you need Composer can also handle global dependencies and their binaries. Usage is straight-forward, all you need
to do is prefix your command with `global`. If for example you wanted to install PHPUnit and have it to do is prefix your command with `global`. If for example you wanted to install PHPUnit and have it
available globally, you'd run the following command: available globally, you'd run the following command:
{% highlight console %} {% highlight console %}
@@ -133,14 +101,14 @@ composer global require phpunit/phpunit
{% endhighlight %} {% endhighlight %}
This will create a `~/.composer` folder where your global dependencies reside. To have the installed This will create a `~/.composer` folder where your global dependencies reside. To have the installed
packages' binaries available everywhere, you'd then add the `~/.composer/vendor/bin` folder to your packages' binaries available everywhere, you'd then add the `~/.composer/vendor/bin` folder to your
`$PATH` variable. `$PATH` variable.
* [Learn about Composer] * [Learn about Composer]
[Packagist]: http://packagist.org/ [Packagist]: https://packagist.org/
[Twig]: http://twig.sensiolabs.org [Twig]: https://twig.symfony.com/
[VersionEye]: https://www.versioneye.com/ [VersionEye]: https://www.versioneye.com/
[Security Advisories Checker]: https://security.sensiolabs.org/ [Security Advisories Checker]: https://security.sensiolabs.org/
[Learn about Composer]: http://getcomposer.org/doc/00-intro.md [Learn about Composer]: https://getcomposer.org/doc/00-intro.md
[ComposerSetup]: https://getcomposer.org/Composer-Setup.exe [ComposerSetup]: https://getcomposer.org/Composer-Setup.exe

View File

@@ -18,10 +18,10 @@ version conflicts between two projects arise.
### How to install PEAR ### How to install PEAR
You can install PEAR by downloading the `.phar` installer and executing it. The PEAR documentation has You can install PEAR by downloading the `.phar` installer and executing it. The PEAR documentation has
detailed [install instructions][2] for every operating system. detailed [install instructions][2] for every operating system.
If you are using Linux, you can also have a look at your distribution package manager. Debian and Ubuntu, If you are using Linux, you can also have a look at your distribution package manager. Debian and Ubuntu,
for example, have an apt `php-pear` package. for example, have an apt `php-pear` package.
### How to install a package ### How to install a package
@@ -47,7 +47,7 @@ handle your PEAR dependencies. This example will install code from `pear2.php.ne
"repositories": [ "repositories": [
{ {
"type": "pear", "type": "pear",
"url": "http://pear2.php.net" "url": "https://pear2.php.net"
} }
], ],
"require": { "require": {
@@ -80,9 +80,9 @@ $request = new pear2\HTTP\Request();
* [Learn more about using PEAR with Composer][6] * [Learn more about using PEAR with Composer][6]
[1]: http://pear.php.net/ [1]: https://pear.php.net/
[2]: http://pear.php.net/manual/en/installation.getting.php [2]: https://pear.php.net/manual/installation.getting.php
[3]: http://pear.php.net/packages.php [3]: https://pear.php.net/packages.php
[4]: http://pear.php.net/manual/en/guide.users.commandline.channels.php [4]: https://pear.php.net/manual/guide.users.commandline.channels.php
[5]: /#composer_and_packagist [5]: /#composer_and_packagist
[6]: http://getcomposer.org/doc/05-repositories.md#pear [6]: https://getcomposer.org/doc/05-repositories.md#pear

View File

@@ -43,7 +43,7 @@ On DateTime objects you can use standard comparison:
{% highlight php %} {% highlight php %}
<?php <?php
if ($start < $end) { if ($start < $end) {
echo "Start is before end!\n"; echo "Start is before the end!\n";
} }
{% endhighlight %} {% endhighlight %}
@@ -61,10 +61,10 @@ foreach ($periodIterator as $date) {
} }
{% endhighlight %} {% endhighlight %}
A popular PHP API extension is [Carbon](http://carbon.nesbot.com). It inherits everything in the DateTime class, so involves minimal code alterations, but extra features include Localization support, further ways to add, subtract and format a DateTime object, plus a means to test your code by simulating a date and time of your choosing. A popular PHP API extension is [Carbon](https://carbon.nesbot.com/). It inherits everything in the DateTime class, so involves minimal code alterations, but extra features include Localization support, further ways to add, subtract and format a DateTime object, plus a means to test your code by simulating a date and time of your choosing.
* [Read about DateTime][datetime] * [Read about DateTime][datetime]
* [Read about date formatting][dateformat] (accepted date format string options) * [Read about date formatting][dateformat] (accepted date format string options)
[datetime]: http://php.net/book.datetime [datetime]: https://secure.php.net/book.datetime
[dateformat]: http://php.net/function.date [dateformat]: https://secure.php.net/function.date

View File

@@ -14,4 +14,6 @@ lot of the pattern decisions are made for you. But it is still up to you to pick
code you build on top of the framework. If, on the other hand, you are not using a framework to build your application code you build on top of the framework. If, on the other hand, you are not using a framework to build your application
then you have to find the patterns that best suit the type and size of application that you're building. then you have to find the patterns that best suit the type and size of application that you're building.
* Continue reading on [Design Patterns](/pages/Design-Patterns.html) You can learn more about PHP design patterns and see working examples at:
<https://designpatternsphp.readthedocs.io/>

View File

@@ -6,7 +6,7 @@ anchor: php_and_utf8
## Working with UTF-8 {#php_and_utf8_title} ## Working with UTF-8 {#php_and_utf8_title}
_This section was originally written by [Alex Cabal](https://alexcabal.com/) over at _This section was originally written by [Alex Cabal](https://alexcabal.com/) over at
[PHP Best Practices](https://phpbestpractices.org/#utf-8) and has been used as the basis for our own UTF-8 advice_. [PHP Best Practices](https://phpbestpractices.org/#utf-8) and has been used as the basis for our own UTF-8 advice_.
### There's no one-liner. Be careful, detailed, and consistent. ### There's no one-liner. Be careful, detailed, and consistent.
@@ -44,7 +44,7 @@ Finally, If you are building a distributed application and cannot be certain tha
enabled, then consider using the [patchwork/utf8] Composer package. This will use `mbstring` if it is available, and 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. fall back to non UTF-8 functions if not.
[Multibyte String Extension]: http://php.net/book.mbstring [Multibyte String Extension]: https://secure.php.net/book.mbstring
[patchwork/utf8]: https://packagist.org/packages/patchwork/utf8 [patchwork/utf8]: https://packagist.org/packages/patchwork/utf8
### UTF-8 at the Database level ### UTF-8 at the Database level
@@ -63,26 +63,30 @@ Further Reading for why.
Use the `mb_http_output()` function to ensure that your PHP script outputs UTF-8 strings to your browser. Use the `mb_http_output()` function to ensure that your PHP script outputs UTF-8 strings to your browser.
The browser will then need to be told by the HTTP response that this page should be considered as UTF-8. The historic The browser will then need to be told by the HTTP response that this page should be considered as UTF-8. Today, it is common to set the character set in the HTTP response header like this:
approach to doing that was to include the [charset `<meta>` tag](http://htmlpurifier.org/docs/enduser-utf8.html) in
your page's `<head>` tag. This approach is perfectly valid, but setting the charset in the `Content-Type` header is {% highlight php %}
actually [much faster](https://developers.google.com/speed/docs/best-practices/rendering#SpecifyCharsetEarly). <?php
header('Content-Type: text/html; charset=UTF-8')
{% endhighlight %}
The historic approach to doing that was to include the [charset `<meta>` tag](http://htmlpurifier.org/docs/enduser-utf8.html) in your page's `<head>` tag.
{% highlight php %} {% highlight php %}
<?php <?php
// Tell PHP that we're using UTF-8 strings until the end of the script // Tell PHP that we're using UTF-8 strings until the end of the script
mb_internal_encoding('UTF-8'); mb_internal_encoding('UTF-8');
// Tell PHP that we'll be outputting UTF-8 to the browser // Tell PHP that we'll be outputting UTF-8 to the browser
mb_http_output('UTF-8'); mb_http_output('UTF-8');
// Our UTF-8 test string // Our UTF-8 test string
$string = 'Êl síla erin lû e-govaned vîn.'; $string = 'Êl síla erin lû e-govaned vîn.';
// Transform the string in some way with a multibyte function // Transform the string in some way with a multibyte function
// Note how we cut the string at a non-Ascii character for demonstration purposes // Note how we cut the string at a non-Ascii character for demonstration purposes
$string = mb_substr($string, 0, 15); $string = mb_substr($string, 0, 15);
// Connect to a database to store the transformed string // Connect to a database to store the transformed string
// See the PDO example in this document for more information // See the PDO example in this document for more information
// Note the `charset=utf8mb4` in the Data Source Name (DSN) // Note the `charset=utf8mb4` in the Data Source Name (DSN)
@@ -95,19 +99,19 @@ $link = new PDO(
PDO::ATTR_PERSISTENT => false PDO::ATTR_PERSISTENT => false
) )
); );
// Store our transformed string as UTF-8 in our database // Store our transformed string as UTF-8 in our database
// Your DB and tables are in the utf8mb4 character set and collation, right? // Your DB and tables are in the utf8mb4 character set and collation, right?
$handle = $link->prepare('insert into ElvishSentences (Id, Body) values (?, ?)'); $handle = $link->prepare('insert into ElvishSentences (Id, Body) values (?, ?)');
$handle->bindValue(1, 1, PDO::PARAM_INT); $handle->bindValue(1, 1, PDO::PARAM_INT);
$handle->bindValue(2, $string); $handle->bindValue(2, $string);
$handle->execute(); $handle->execute();
// Retrieve the string we just stored to prove it was stored correctly // Retrieve the string we just stored to prove it was stored correctly
$handle = $link->prepare('select * from ElvishSentences where Id = ?'); $handle = $link->prepare('select * from ElvishSentences where Id = ?');
$handle->bindValue(1, 1, PDO::PARAM_INT); $handle->bindValue(1, 1, PDO::PARAM_INT);
$handle->execute(); $handle->execute();
// Store the result into an object that we'll output later in our HTML // Store the result into an object that we'll output later in our HTML
$result = $handle->fetchAll(\PDO::FETCH_OBJ); $result = $handle->fetchAll(\PDO::FETCH_OBJ);
@@ -130,23 +134,21 @@ header('Content-Type: text/html; charset=UTF-8');
### Further reading ### Further reading
* [PHP Manual: String Operations](http://php.net/language.operators.string) * [PHP Manual: String Operations](https://secure.php.net/language.operators.string)
* [PHP Manual: String Functions](http://php.net/ref.strings) * [PHP Manual: String Functions](https://secure.php.net/ref.strings)
* [`strpos()`](http://php.net/function.strpos) * [`strpos()`](https://secure.php.net/function.strpos)
* [`strlen()`](http://php.net/function.strlen) * [`strlen()`](https://secure.php.net/function.strlen)
* [`substr()`](http://php.net/function.substr) * [`substr()`](https://secure.php.net/function.substr)
* [PHP Manual: Multibyte String Functions](http://php.net/ref.mbstring) * [PHP Manual: Multibyte String Functions](https://secure.php.net/ref.mbstring)
* [`mb_strpos()`](http://php.net/function.mb-strpos) * [`mb_strpos()`](https://secure.php.net/function.mb-strpos)
* [`mb_strlen()`](http://php.net/function.mb-strlen) * [`mb_strlen()`](https://secure.php.net/function.mb-strlen)
* [`mb_substr()`](http://php.net/function.mb-substr) * [`mb_substr()`](https://secure.php.net/function.mb-substr)
* [`mb_internal_encoding()`](http://php.net/function.mb-internal-encoding) * [`mb_internal_encoding()`](https://secure.php.net/function.mb-internal-encoding)
* [`mb_http_output()`](http://php.net/function.mb-http-output) * [`mb_http_output()`](https://secure.php.net/function.mb-http-output)
* [`htmlentities()`](http://php.net/function.htmlentities) * [`htmlentities()`](https://secure.php.net/function.htmlentities)
* [`htmlspecialchars()`](http://php.net/function.htmlspecialchars) * [`htmlspecialchars()`](https://secure.php.net/function.htmlspecialchars)
* [PHP UTF-8 Cheatsheet](http://blog.loftdigital.com/blog/php-utf-8-cheatsheet) * [Stack Overflow: What factors make PHP Unicode-incompatible?](https://stackoverflow.com/questions/571694/what-factors-make-php-unicode-incompatible)
* [Handling UTF-8 with PHP](http://www.phpwact.org/php/i18n/utf-8) * [Stack Overflow: Best practices in PHP and MySQL with international strings](https://stackoverflow.com/questions/140728/best-practices-in-php-and-mysql-with-international-strings)
* [Stack Overflow: What factors make PHP Unicode-incompatible?](http://stackoverflow.com/questions/571694/what-factors-make-php-unicode-incompatible) * [How to support full Unicode in MySQL databases](https://mathiasbynens.be/notes/mysql-utf8mb4)
* [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) * [Bringing Unicode to PHP with Portable UTF-8](https://www.sitepoint.com/bringing-unicode-to-php-with-portable-utf8/)
* [How to support full Unicode in MySQL databases](http://mathiasbynens.be/notes/mysql-utf8mb4) * [Stack Overflow: DOMDocument loadHTML does not encode UTF-8 correctly](https://stackoverflow.com/questions/8218230/php-domdocument-loadhtml-not-encoding-utf-8-correctly)
* [Bringing Unicode to PHP with Portable UTF-8](http://www.sitepoint.com/bringing-unicode-to-php-with-portable-utf8/)
* [Stack Overflow: DOMDocument loadHTML does not encode UTF-8 correctly](http://stackoverflow.com/questions/8218230/php-domdocument-loadhtml-not-encoding-utf-8-correctly)

View File

@@ -12,39 +12,41 @@ words - in our case, internationalization becomes i18n and localization, l10n._
First of all, we need to define those two similar concepts and other related things: First of all, we need to define those two similar concepts and other related things:
- **Internationalization** is when you organize your code so it can be adapted to different languages or regions - **Internationalization** is when you organize your code so it can be adapted to different languages or regions
without refactorings. This is usually done once - preferably, in the beginning of the project, or else you'll probably without refactorings. This action is usually done once - preferably, at the beginning of the project, or else you will
need some huge changes in the source! probably need some huge changes in the source!
- **Localization** happens when you adapt the interface (mainly) by translating contents, based on the i18n work done - **Localization** happens when you adapt the interface (mainly) by translating contents, based on the i18n work done
before. It usually is done every time a new language or region needs support and is updated when new interface pieces before. It usually is done every time a new language or region needs support and is updated when new interface pieces
are added, as they need to be available in all supported languages. are added, as they need to be available in all supported languages.
- **Pluralization** defines the rules needed between different languages to interoperate strings containing numbers and - **Pluralization** defines the rules required between distinct languages to interoperate strings containing numbers and
counters. For instance, in English when you have only one item, it's singular, and anything different from that is counters. For instance, in English when you have only one item, it is singular, and anything different from that is
called plural; plural in this language is indicated by adding an S after some words, and sometimes changes parts of it. called plural; plural in this language is indicated by adding an S after some words, and sometimes changes parts of it.
In other languages, such as Russian or Serbian, there are two plural forms in addition to the singular - you may even In other languages, such as Russian or Serbian, there are two plural forms in addition to the singular - you may even
find languages with a total of four, five or six forms, such as Slovenian, Irish or Arabic. find languages with a total of four, five or six forms, such as Slovenian, Irish or Arabic.
## Common ways to implement ## Common ways to implement
The easiest way to internationalize PHP software is by using array files and using those strings in templates, such as The easiest way to internationalize PHP software is by using array files and using those strings in templates, such as
`<h1><?=$TRANS['title_about_page']?></h1>`. This is, however, hardly a recommended way for serious projects, as it poses `<h1><?=$TRANS['title_about_page']?></h1>`. This way is, however, hardly recommended for serious projects, as it poses
some maintenance issues along the road - some might appear in the very beginning, such as pluralization. So, please, some maintenance issues along the road - some might appear in the very beginning, such as pluralization. So, please,
don't try this if your project will contain more than a couple of pages. don't try this if your project will contain more than a couple of pages.
The most classic way and often taken as reference for i18n and l10n is a [Unix tool called `gettext`][gettext]. It dates The most classic way and often taken as reference for i18n and l10n is a [Unix tool called `gettext`][gettext]. It dates
back to 1995 and is still a complete implementation for translating software. It is pretty easy to get running, while back to 1995 and is still a complete implementation for translating software. It is easy enough to get running, while
it still sports powerful supporting tools. It's about Gettext we will be talking here. Also, to help you not get messy still sporting powerful supporting tools. It is about Gettext we will be talking here. Also, to help you not get messy
over the command-line, we will be presenting a great GUI application that can be used to easily update your l10n source over the command-line, we will be presenting a great GUI application that can be used to easily update your l10n source
files.
### Other tools ### Other tools
There are common libraries used that support Gettext and other implementations of i18n. Some of them may seem easier to There are common libraries used that support Gettext and other implementations of i18n. Some of them may seem easier to
install or sport additional features or i18n file formats. In this document, we focus on the tools provided with the install or sport additional features or i18n file formats. In this document, we focus on the tools provided with the
PHP core, but here we list others for completion: PHP core, but here we list others for completion:
- [aura/intl][aura-intl]: Provides internationalization (I18N) tools, specifically package-oriented per-locale message
translation. It uses array formats for message. Does not provide a message extractor, but does provide advanced
message formatting via the `intl` extension (including pluralized messages).
- [oscarotero/Gettext][oscarotero]: Gettext support with an OO interface; includes improved helper functions, powerful - [oscarotero/Gettext][oscarotero]: Gettext support with an OO interface; includes improved helper functions, powerful
extractors for several file formats (some of them not supported natively by the `gettext` command), and can also export extractors for several file formats (some of them not supported natively by the `gettext` command), and can also export
to other formats besides `.mo/.po` files. Can be useful if you need to integrate your translation files into other parts to other formats besides `.mo/.po` files. Can be useful if you need to integrate your translation files into other
of the system, like a JavaScript interface. parts of the system, like a JavaScript interface.
- [symfony/translation][symfony]: supports a lot of different formats, but recommends using verbose XLIFF's. Doesn't - [symfony/translation][symfony]: supports a lot of different formats, but recommends using verbose XLIFF's. Doesn't
include helper functions nor a built-in extractor, but supports placeholders using `strtr()` internally. include helper functions nor a built-in extractor, but supports placeholders using `strtr()` internally.
- [zend/i18n][zend]: supports array and INI files, or Gettext formats. Implements a caching layer to save you from - [zend/i18n][zend]: supports array and INI files, or Gettext formats. Implements a caching layer to save you from
@@ -52,6 +54,7 @@ reading the filesystem every time. It also includes view helpers, and locale-awa
However, it has no message extractor. However, it has no message extractor.
Other frameworks also include i18n modules, but those are not available outside of their codebases: Other frameworks also include i18n modules, but those are not available outside of their codebases:
- [Laravel] supports basic array files, has no automatic extractor but includes a `@lang` helper for template files. - [Laravel] supports basic array files, has no automatic extractor but includes a `@lang` helper for template files.
- [Yii] supports array, Gettext, and database-based translation, and includes a messages extractor. It is backed by the - [Yii] supports array, Gettext, and database-based translation, and includes a messages extractor. It is backed by the
[`Intl`][intl] extension, available since PHP 5.3, and based on the [ICU project]; this enables Yii to run powerful [`Intl`][intl] extension, available since PHP 5.3, and based on the [ICU project]; this enables Yii to run powerful
@@ -68,7 +71,7 @@ After installed, enable it by adding `extension=gettext.so` (Linux/Unix) or `ext
your `php.ini`. your `php.ini`.
Here we will also be using [Poedit] to create translation files. You will probably find it in your system's package Here we will also be using [Poedit] to create translation files. You will probably find it in your system's package
manager; it's available for Unix, Mac, and Windows, and can be [downloaded for free on their website][poedit_download] manager; it is available for Unix, Mac, and Windows, and can be [downloaded for free on their website][poedit_download]
as well. as well.
### Structure ### Structure
@@ -76,31 +79,31 @@ as well.
#### Types of files #### Types of files
There are three files you usually deal with while working with gettext. The main ones are PO (Portable Object) and There are three files you usually deal with while working with gettext. The main ones are PO (Portable Object) and
MO (Machine Object) files, the first being a list of readable "translated objects" and the second, the corresponding MO (Machine Object) files, the first being a list of readable "translated objects" and the second, the corresponding
binary to be interpreted by gettext when doing localization. There's also a POT (Template) file, that simply contains binary to be interpreted by gettext when doing localization. There's also a POT (Template) file, which simply contains
all existing keys from your source files, and can be used as a guide to generate and update all PO files. Those template all existing keys from your source files, and can be used as a guide to generate and update all PO files. Those template
files are not mandatory: depending on the tool you're using to do l10n, you can go just fine with only PO/MO files. files are not mandatory: depending on the tool you are using to do l10n, you can go just fine with only PO/MO files.
You'll always have one pair of PO/MO files per language and region, but only one POT per domain. You will always have one pair of PO/MO files per language and region, but only one POT per domain.
### Domains ### Domains
There are some cases, in big projects, where you might need to separate translations when the same words convey There are some cases, in big projects, where you might need to separate translations when the same words convey
different meaning given a context. In those cases, you split them into different _domains_. They're basically named different meaning given a context. In those cases, you split them into different _domains_. They are, basically, named
groups of POT/PO/MO files, where the filename is the said _translation domain_. Small and medium-sized projects usually, groups of POT/PO/MO files, where the filename is the said _translation domain_. Small and medium-sized projects usually,
for simplicity, use only one domain; its name is arbitrary, but we will be using "main" for our code samples. for simplicity, use only one domain; its name is arbitrary, but we will be using "main" for our code samples.
In [Symfony] projects, for example, domains are used to separate the translation for validation messages. In [Symfony] projects, for example, domains are used to separate the translation for validation messages.
#### Locale code #### Locale code
A locale is simply a code that identifies one version of a language. It's defined following the [ISO 639-1][639-1] and A locale is simply a code that identifies one version of a language. It is defined following the [ISO 639-1][639-1] and
[ISO 3166-1 alpha-2][3166-1] specs: two lower-case letters for the language, optionally followed by an underline and two [ISO 3166-1 alpha-2][3166-1] specs: two lower-case letters for the language, optionally followed by an underline and two
upper-case letters identifying the country or regional code. For [rare languages][rare], three letters are used. upper-case letters identifying the country or regional code. For [rare languages][rare], three letters are used.
For some speakers, the country part may seem redundant. In fact, some languages have dialects in different For some speakers, the country part may seem redundant. In fact, some languages have dialects in different
countries, such as Austrian German (`de_AT`) or Brazilian Portuguese (`pt_BR`). The second part is used to distinguish countries, such as Austrian German (`de_AT`) or Brazilian Portuguese (`pt_BR`). The second part is used to distinguish
between those dialects - when it's not present, it's taken as a "generic" or "hybrid" version of the language. between those dialects - when it is not present, it is taken as a "generic" or "hybrid" version of the language.
### Directory structure ### Directory structure
To use Gettext, we will need to adhere to a specific structure of folders. First, you'll need to select an arbitrary To use Gettext, we will need to adhere to a specific structure of folders. First, you will need to select an arbitrary
root for your l10n files in your source repository. Inside it, you'll have a folder for each needed locale, and a fixed root for your l10n files in your source repository. Inside it, you will have a folder for each needed locale, and a
`LC_MESSAGES` folder that will contain all your PO/MO pairs. Example: fixed `LC_MESSAGES` folder that will contain all your PO/MO pairs. Example:
{% highlight console %} {% highlight console %}
<project root> <project root>
@@ -128,9 +131,9 @@ root for your l10n files in your source repository. Inside it, you'll have a fol
### Plural forms ### Plural forms
As we said in the introduction, different languages might sport different plural rules. However, gettext saves us from As we said in the introduction, different languages might sport different plural rules. However, gettext saves us from
this trouble once again. When creating a new `.po` file, you'll have to declare the [plural rules][plural] for that this trouble once again. When creating a new `.po` file, you will have to declare the [plural rules][plural] for that
language, and translated pieces that are plural-sensitive will have a different form for each of those rules. When language, and translated pieces that are plural-sensitive will have a different form for each of those rules. When
calling Gettext in code, you'll have to specify the number related to the sentence, and it will work out the correct calling Gettext in code, you will have to specify the number related to the sentence, and it will work out the correct
form to use - even using string substitution if needed. form to use - even using string substitution if needed.
Plural rules include the number of plurals available and a boolean test with `n` that would define in which rule the Plural rules include the number of plurals available and a boolean test with `n` that would define in which rule the
@@ -141,16 +144,16 @@ given number falls (starting the count with 0). For example:
- Brazilian Portuguese: `nplurals=2; plural=(n > 1);` - two rules, second if N is bigger than one, first otherwise - Brazilian Portuguese: `nplurals=2; plural=(n > 1);` - two rules, second if N is bigger than one, first otherwise
Now that you understood the basis of how plural rules works - and if you didn't, please look at a deeper explanation Now that you understood the basis of how plural rules works - and if you didn't, please look at a deeper explanation
on the [LingoHub tutorial](lingohub_plurals) -, you might want to copy the ones you need from a [list][plural] instead on the [LingoHub tutorial][lingohub_plurals] -, you might want to copy the ones you need from a [list][plural] instead
of writing them by hand. of writing them by hand.
When calling out Gettext to do localization on sentences with counters, you'll have to give him the When calling out Gettext to do localization on sentences with counters, you will have to give him the
related number as well. Gettext will work out what rule should be in effect and use the correct localized version. related number as well. Gettext will work out what rule should be in effect and use the correct localized version.
You will need to include in the `.po` file a different sentence for each plural rule defined. You will need to include in the `.po` file a different sentence for each plural rule defined.
### Sample implementation ### Sample implementation
After all that theory, let's get a little practical. Here's an excerpt of a `.po` file - don't mind with its format, After all that theory, let's get a little practical. Here's an excerpt of a `.po` file - don't mind with its format,
but instead the overall content, you'll learn how to edit it easily later: but with the overall content instead; you will learn how to edit it easily later:
{% highlight po %} {% highlight po %}
msgid "" msgid ""
@@ -159,7 +162,7 @@ msgstr ""
"Content-Type: text/plain; charset=UTF-8\n" "Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n"
msgid "We're now translating some strings" msgid "We are now translating some strings"
msgstr "Nós estamos traduzindo algumas strings agora" msgstr "Nós estamos traduzindo algumas strings agora"
msgid "Hello %1$s! Your last visit was on %2$s" msgid "Hello %1$s! Your last visit was on %2$s"
@@ -174,51 +177,51 @@ msgstr[1] "%d mensagens não lidas"
The first section works like a header, having the `msgid` and `msgstr` especially empty. It describes the file encoding, The first section works like a header, having the `msgid` and `msgstr` especially empty. It describes the file encoding,
plural forms and other things that are less relevant. plural forms and other things that are less relevant.
The second section translates a simple string from English to The second section translates a simple string from English to
Brazilian Portuguese, and the third does the same, but leveraging string replacement from [`sprintf`](sprintf) so the Brazilian Portuguese, and the third does the same, but leveraging string replacement from [`sprintf`][sprintf] so the
translation may contain the user name and visit date. translation may contain the user name and visit date.
The last section is a sample of pluralization forms, displaying The last section is a sample of pluralization forms, displaying
the singular and plural version as `msgid` in English and their corresponding translations as `msgstr` 0 and 1 the singular and plural version as `msgid` in English and their corresponding translations as `msgstr` 0 and 1
(following the number given by the plural rule). There, string replacement is used as well so the number can be seen (following the number given by the plural rule). There, string replacement is used as well so the number can be seen
directly in the sentence, by using `%d`. The plural forms always have two `msgid` (singular and plural), so it's directly in the sentence, by using `%d`. The plural forms always have two `msgid` (singular and plural), so it is
advised to not use a complex language as the source of translation. advised not to use a complex language as the source of translation.
### Discussion on l10n keys ### Discussion on l10n keys
As you might have noticed, we're using as source ID the actual sentence in English. That `msgid` is the same used As you might have noticed, we are using as source ID the actual sentence in English. That `msgid` is the same used
throughout all your `.po` files, meaning other languages will have the same format and the same `msgid` fields but throughout all your `.po` files, meaning other languages will have the same format and the same `msgid` fields but
translated `msgstr` lines. translated `msgstr` lines.
Talking about translation keys, there are two main "schools" here: Talking about translation keys, there are two main "schools" here:
1. _`msgid` as a real sentence_. 1. _`msgid` as a real sentence_.
The main advantages are: The main advantages are:
- if there are pieces of the software untranslated in any given language, the key displayed will still maintain some - if there are pieces of the software untranslated in any given language, the key displayed will still maintain some
meaning. Example: if you happen to translate by heart from English to Spanish but need help to translate to French, meaning. Example: if you happen to translate by heart from English to Spanish but need help to translate to French,
you might publish the new page with missing French sentences, and parts of the website would be displayed in English you might publish the new page with missing French sentences, and parts of the website would be displayed in English
instead; instead;
- it's much easier for the translator to understand what's going on and make a proper translation based on the - it is much easier for the translator to understand what's going on and do a proper translation based on the
`msgid`; `msgid`;
- it gives you "free" l10n for one language - the source one; - it gives you "free" l10n for one language - the source one;
- The only disadvantage: if you need to change the actual text, you would need to replace the same `msgid` - The only disadvantage: if you need to change the actual text, you would need to replace the same `msgid`
across several language files. across several language files.
2. _`msgid` as a unique, structured key_. 2. _`msgid` as a unique, structured key_.
It would describe the sentence role in the application in a structured way, including the template or part where the It would describe the sentence role in the application in a structured way, including the template or part where the
string is located instead of its content. string is located instead of its content.
- it's a great way to have the code organized, separating the text content from the template logic. - it is a great way to have the code organized, separating the text content from the template logic.
- however, that could bring problems to the translator that would miss the context. A source language file would be - however, that could bring problems to the translator that would miss the context. A source language file would be
needed as a basis for other translations. Example: the developer would ideally have an `en.po` file, that needed as a basis for other translations. Example: the developer would ideally have an `en.po` file, that
translators would read to understand what to write in `fr.po` for instance. translators would read to understand what to write in `fr.po` for instance.
- missing translations would display meaningless keys on screen (`top_menu.welcome` instead of `Hello there, User!` - missing translations would display meaningless keys on screen (`top_menu.welcome` instead of `Hello there, User!`
on the said untranslated French page). That's good it as would force translation to be complete before publishing - on the said untranslated French page). That is good it as would force translation to be complete before publishing -
but bad as translation issues would be really awful in the interface. Some libraries, though, include an option to however, bad as translation issues would be remarkably awful in the interface. Some libraries, though, include an
specify a given language as "fallback", having a similar behavior as the other approach. option to specify a given language as "fallback", having a similar behavior as the other approach.
The [Gettext manual][manual] favors the first approach as, in general, it's easier for translators and users in The [Gettext manual][manual] favors the first approach as, in general, it is easier for translators and users in
case of trouble. That's how we will be working here as well. However, the [Symfony documentation][symfony-keys] favors case of trouble. That is how we will be working here as well. However, the [Symfony documentation][symfony-keys] favors
keyword-based translation, to allow for independent changes of all translations without affecting templates as well. keyword-based translation, to allow for independent changes of all translations without affecting templates as well.
### Everyday usage ### Everyday usage
In a common application, you would use some Gettext functions while writing static text in your pages. Those sentences In a typical application, you would use some Gettext functions while writing static text in your pages. Those sentences
would then appear in `.po` files, get translated, compiled into `.mo` files and then, used by Gettext when rendering would then appear in `.po` files, get translated, compiled into `.mo` files and then, used by Gettext when rendering
the actual interface. Given that, let's tie together what we have discussed so far in a step-by-step example: the actual interface. Given that, let's tie together what we have discussed so far in a step-by-step example:
@@ -257,7 +260,7 @@ call. More on domain configuration in the next example.
* @return bool * @return bool
*/ */
function valid($locale) { function valid($locale) {
return in_array($locale, ['en_US', 'en', 'pt_BR', 'pt', 'es_ES', 'es'); return in_array($locale, ['en_US', 'en', 'pt_BR', 'pt', 'es_ES', 'es']);
} }
//setting the source/default locale, for informational purposes //setting the source/default locale, for informational purposes
@@ -307,69 +310,76 @@ textdomain('main');
{% endhighlight %} {% endhighlight %}
#### 3. Preparing translation for the first run #### 3. Preparing translation for the first run
To make matters easier - and one of the powerful advantages Gettext has over custom framework i18n packages - is its One of the great advantages Gettext has over custom framework i18n packages is its extensive and powerful file format.
custom file type. "Oh man, that's quite hard to understand and edit by hand, a simple array would be easier!" Make no "Oh man, thats quite hard to understand and edit by hand, a simple array would be easier!" Make no mistake,
mistake, applications like [Poedit] are here to help - _a lot_. You can get the program from applications like [Poedit] are here to help - _a lot_. You can get the program from [their website][poedit_download],
[their website](poedit_download), it's free and available for all platforms. It's a pretty easy tool to get used to, its free and available for all platforms. Its a pretty easy tool to get used to, and a very powerful one at the same
and a very powerful one at the same time - using all powerful features Gettext has available. time - using all features Gettext has available. This guide is based on PoEdit 1.8.
In the first run, you should select "File > New Catalog" from the menu. There you'll have a small screen where we will In the first run, you should select File > New...” from the menu. Youll be asked straight ahead for the language:
set the terrain so everything else runs smoothly. You'll be able to find those settings later through here you can select/filter the language you want to translate to, or use that format we mentioned before, such as
"Catalog > Properties": `en_US` or `pt_BR`.
- Project name and version, Translation Team and email address: useful information that goes in the `.po` file header; Now, save the file - using that directory structure we mentioned as well. Then you should click “Extract from sources”,
- Language: here you should use that format we mentioned before, such as `en_US` or `pt_BR`; and here youll configure various settings for the extraction and translation tasks. Youll be able to find all those
- Charsets: UTF-8, preferably; later through “Catalog > Properties”:
- Source charset: set here the charset used by your PHP files - probably UTF-8 as well, right?
- plural forms: here go those rules we mentioned before - there's a link in there with samples as well;
- Source paths: here you must include all folders from the project where `gettext()` (and siblings) will happen - this
is usually your templates folder(s)
- Source keywords: this last part is filled by default, but you might need to alter it later - and is one of the
powerful points of Gettext. The underlying software knows how the `gettext()` calls look like in several programming
languages, but you might as well create your own translation forms. This will be discussed later in the "Tips" section.
After setting those points you'll be prompted to save the file - using that directory structure we mentioned as well, - Source paths: here you must include all folders from the project where `gettext()` (and siblings) are called - this
and then it will run a scan through your source files to find the localization calls. They'll be fed empty into the is usually your templates/views folder(s). This is the only mandatory setting;
translation table, and you'll start typing in the localized versions of those strings. Save it and a `.mo` file will be - Translation properties:
(re)compiled into the same folder and ta-dah: your project is internationalized. - Project name and version, Team and Teams email address: useful information that goes in the .po file header;
- Plural forms: here go those rules we mentioned before - theres a link in there with samples as well. You can
leave it with the default option most of the time, as PoEdit already includes a handy database of plural rules for
many languages.
- Charsets: UTF-8, preferably;
- Source code charset: set here the charset used by your codebase - probably UTF-8 as well, right?
- Source keywords: The underlying software knows how `gettext()` and similar function calls look like in several
programming languages, but you might as well create your own translation functions. It will be here youll add those
other methods. This will be discussed later in the “Tips” section.
After setting those points it will run a scan through your source files to find all the localization calls. After every
scan PoEdit will display a summary of what was found and what was removed from the source files. New entries will fed
empty into the translation table, and youll start typing in the localized versions of those strings. Save it and a .mo
file will be (re)compiled into the same folder and ta-dah: your project is internationalized.
#### 4. Translating strings #### 4. Translating strings
As you may have noticed before, there are two main types of localized strings: simple ones and the ones with plural As you may have noticed before, there are two main types of localized strings: simple ones and those with plural
forms. The first ones have simply two boxes: source and localized string. The source string can't be modified as forms. The first ones have simply two boxes: source and localized string. The source string cannot be modified as
Gettext/Poedit do not include the powers to alter your source files - you should change the source itself and rescan Gettext/Poedit do not include the powers to alter your source files - you should change the source itself and rescan
the files. Tip: you may right-click a translation line and it will hint you with the source files and lines where that the files. Tip: you may right-click a translation line and it will hint you with the source files and lines where that
string is being used. string is being used.
On the other hand, plural form strings include two boxes to show the two source strings, and tabs so you can configure On the other hand, plural form strings include two boxes to show the two source strings, and tabs so you can configure
the different final forms. the different final forms.
Whenever you change your sources and need to update the translations, just hit Refresh and Poedit will rescan the code, Whenever you change your sources and need to update the translations, just hit Refresh and Poedit will rescan the code,
removing non-existent entries, merging the ones that changed and adding new ones. It may also try to guess some removing non-existent entries, merging the ones that changed and adding new ones. It may also try to guess some
translations, based on other ones you did. Those guesses and the changed entries will receive a "Fuzzy" marker, translations, based on other ones you did. Those guesses and the changed entries will receive a "Fuzzy" marker,
indicating it needs review, being highlighted in the list. It's also useful if you have a translation team and someone indicating it needs review, appearing golden in the list. It is also useful if you have a translation team and someone
tries to write something they're not sure about: just mark Fuzzy and someone else will review later. tries to write something they are not sure about: just mark Fuzzy, and someone else will review later.
Finally, it's advised to leave "View > Untranslated entries first" marked, as it will help you _a lot_ to not forget Finally, it is advised to leave "View > Untranslated entries first" marked, as it will help you _a lot_ to not forget
any entry. From that menu, you can also open parts of the UI that allow you to leave contextual information for any entry. From that menu, you can also open parts of the UI that allow you to leave contextual information for
translators if needed. translators if needed.
### Tips & Tricks ### Tips & Tricks
#### Possible caching issues #### Possible caching issues
If you're running PHP as a module on Apache (`mod_php`), you might face issues with the `.mo` file being cached. It If you are running PHP as a module on Apache (`mod_php`), you might face issues with the `.mo` file being cached. It
happens the first time it's read, and then, to update it, you might need to restart the server. On Nginx and PHP5 it happens the first time it is read, and then, to update it, you might need to restart the server. On Nginx and PHP5 it
usually takes only a couple of page refreshes to refresh the translation cache, and on PHP7 it is rarely needed. usually takes only a couple of page refreshes to refresh the translation cache, and on PHP7 it is rarely needed.
#### Additional helper functions #### Additional helper functions
As preferred by many people, it's easier to use `_()` instead of `gettext()`. Many custom i18n libraries from As preferred by many people, it is easier to use `_()` instead of `gettext()`. Many custom i18n libraries from
frameworks use something similar to `t()` as well, to make translated code shorter. However, that's the only function frameworks use something similar to `t()` as well, to make translated code shorter. However, that is the only function
that sports a shortcut. You might want to add in your project some others, such as `__()` or `_n()` for `ngettext()`, that sports a shortcut. You might want to add in your project some others, such as `__()` or `_n()` for `ngettext()`,
or maybe a fancy `_r()` that would join `gettext()` and `sprintf()` calls. Other libraries, such as or maybe a fancy `_r()` that would join `gettext()` and `sprintf()` calls. Other libraries, such as
[oscarotero's Gettext][oscarotero] also provide helper functions like these. [oscarotero's Gettext][oscarotero] also provide helper functions like these.
In those cases, you'll need to instruct the Gettext utility on how to extract the strings from those new functions. In those cases, you'll need to instruct the Gettext utility on how to extract the strings from those new functions.
Don't be afraid, it's very easy. It's just a field in the `.po` file, or a Settings screen on Poedit. In the editor, Don't be afraid; it is very easy. It is just a field in the `.po` file, or a Settings screen on Poedit. In the editor,
that option is inside "Catalog > Properties > Source keywords". You need to include there the specifications of those that option is inside "Catalog > Properties > Source keywords". Remember: Gettext already knows the default functions
new functions, following [a specific format](func_format): for many languages, so dont be afraid if that list seems empty. You need to include there the specifications of those
new functions, following [a specific format][func_format]:
- if you create something like `t()` that simply returns the translation for a string, you can specify it as `t`. - if you create something like `t()` that simply returns the translation for a string, you can specify it as `t`.
Gettext will know the only function argument is the string to be translated; Gettext will know the only function argument is the string to be translated;
@@ -385,8 +395,8 @@ After including those new rules in the `.po` file, a new scan will bring in your
* [Wikipedia: i18n and l10n](https://en.wikipedia.org/wiki/Internationalization_and_localization) * [Wikipedia: i18n and l10n](https://en.wikipedia.org/wiki/Internationalization_and_localization)
* [Wikipedia: Gettext](https://en.wikipedia.org/wiki/Gettext) * [Wikipedia: Gettext](https://en.wikipedia.org/wiki/Gettext)
* [LingoHub: PHP internationalization with gettext tutorial](lingohub) * [LingoHub: PHP internationalization with gettext tutorial][lingohub]
* [PHP Manual: Gettext](http://php.net/manual/en/book.gettext.php) * [PHP Manual: Gettext](https://secure.php.net/manual/book.gettext.php)
* [Gettext Manual][manual] * [Gettext Manual][manual]
[Poedit]: https://poedit.net [Poedit]: https://poedit.net
@@ -395,22 +405,23 @@ After including those new rules in the `.po` file, a new scan will bring in your
[lingohub_plurals]: https://lingohub.com/blog/2013/07/php-internationalization-with-gettext-tutorial/#Plurals [lingohub_plurals]: https://lingohub.com/blog/2013/07/php-internationalization-with-gettext-tutorial/#Plurals
[plural]: http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html [plural]: http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
[gettext]: https://en.wikipedia.org/wiki/Gettext [gettext]: https://en.wikipedia.org/wiki/Gettext
[manual]: http://www.gnu.org/software/gettext/manual/gettext.html [manual]: https://www.gnu.org/software/gettext/manual/gettext.html
[639-1]: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes [639-1]: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
[3166-1]: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 [3166-1]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
[rare]: http://www.gnu.org/software/gettext/manual/gettext.html#Rare-Language-Codes [rare]: https://www.gnu.org/software/gettext/manual/gettext.html#Rare-Language-Codes
[func_format]: https://www.gnu.org/software/gettext/manual/gettext.html#Language-specific-options [func_format]: https://www.gnu.org/software/gettext/manual/gettext.html#Language-specific-options
[aura-intl]: https://github.com/auraphp/Aura.Intl
[oscarotero]: https://github.com/oscarotero/Gettext [oscarotero]: https://github.com/oscarotero/Gettext
[symfony]: https://symfony.com/doc/current/components/translation.html [symfony]: https://symfony.com/doc/current/components/translation.html
[zend]: https://docs.zendframework.com/zend-i18n/translation [zend]: https://docs.zendframework.com/zend-i18n/translation
[laravel]: https://laravel.com/docs/master/localization [laravel]: https://laravel.com/docs/master/localization
[yii]: http://www.yiiframework.com/doc-2.0/guide-tutorial-i18n.html [yii]: https://www.yiiframework.com/doc/guide/2.0/en/tutorial-i18n
[intl]: http://br2.php.net/manual/en/intro.intl.php [intl]: https://secure.php.net/manual/intro.intl.php
[ICU project]: http://www.icu-project.org [ICU project]: http://www.icu-project.org
[symfony-keys]: https://symfony.com/doc/current/components/translation/usage.html#creating-translations [symfony-keys]: https://symfony.com/doc/current/components/translation/usage.html#creating-translations
[sprintf]: http://php.net/manual/en/function.sprintf.php [sprintf]: https://secure.php.net/manual/function.sprintf.php
[func]: http://php.net/manual/en/function.gettext.php [func]: https://secure.php.net/manual/function.gettext.php
[n_func]: http://php.net/manual/en/function.ngettext.php [n_func]: https://secure.php.net/manual/function.ngettext.php
[d_func]: http://php.net/manual/en/function.dgettext.php [d_func]: https://secure.php.net/manual/function.dgettext.php
[dn_func]: http://php.net/manual/en/function.dngettext.php [dn_func]: https://secure.php.net/manual/function.dngettext.php

View File

@@ -5,9 +5,9 @@ anchor: dependency_injection
# Dependency Injection {#dependency_injection_title} # Dependency Injection {#dependency_injection_title}
From [Wikipedia](http://en.wikipedia.org/wiki/Dependency_injection): From [Wikipedia](https://wikipedia.org/wiki/Dependency_injection):
> Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it > Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it
> possible to change them, whether at run-time or compile-time. > possible to change them, whether at run-time or compile-time.
This quote makes the concept sound much more complicated than it actually is. Dependency Injection is providing a This quote makes the concept sound much more complicated than it actually is. Dependency Injection is providing a

View File

@@ -47,6 +47,6 @@ class Database
class MysqlAdapter {} class MysqlAdapter {}
{% endhighlight %} {% endhighlight %}
Now we are giving the `Database` class its dependency rather than it creating it itself. We could even create a method Now we are giving the `Database` class its dependency rather than creating it itself. We could even create a method
that would accept an argument of the dependency and set it that way, or if the `$adapter` property was `public` we that would accept an argument of the dependency and set it that way, or if the `$adapter` property was `public` we
could set it directly. could set it directly.

View File

@@ -15,19 +15,66 @@ separate from our objects. In terms of Dependency Injection, this means loosenin
instantiating them elsewhere in the system. instantiating them elsewhere in the system.
For years, PHP frameworks have been achieving Inversion of Control, however, the question became, which part of control For years, PHP frameworks have been achieving Inversion of Control, however, the question became, which part of control
are you inverting, and where to? For example, MVC frameworks would generally provide a super object or base controller are we inverting, and where to? For example, MVC frameworks would generally provide a super object or base controller
that other controllers must extend to gain access to its dependencies. This **is** Inversion of Control, however, that other controllers must extend to gain access to its dependencies. This **is** Inversion of Control, however,
instead of loosening dependencies, this method simply moved them. instead of loosening dependencies, this method simply moved them.
Dependency Injection allows us to more elegantly solve this problem by only injecting the dependencies we need, when we Dependency Injection allows us to more elegantly solve this problem by only injecting the dependencies we need, when we
need them, without the need for any hard coded dependencies at all. need them, without the need for any hard coded dependencies at all.
### Dependency Inversion Principle ### S.O.L.I.D.
Dependency Inversion Principle is the "D" in the S.O.L.I.D set of object oriented design principles that states one #### Single Responsibility Principle
should *"Depend on Abstractions. Do not depend on concretions."*. Put simply, this means our dependencies should be
interfaces/contracts or abstract classes rather than concrete implementations. We can easily refactor the above example The Single Responsibility Principle is about actors and high-level architecture. It states that “A class should have
to follow this principle. only one reason to change.” This means that every class should _only_ have responsibility over a single part of the
functionality provided by the software. The largest benefit of this approach is that it enables improved code
_reusability_. By designing our class to do just one thing, we can use (or re-use) it in any other program without
changing it.
#### Open/Closed Principle
The Open/Closed Principle is about class design and feature extensions. It states that “Software entities (classes,
modules, functions, etc.) should be open for extension, but closed for modification.” This means that we should design
our modules, classes and functions in a way that when a new functionality is needed, we should not modify our existing
code but rather write new code that will be used by existing code. Practically speaking, this means that we should write
classes that implement and adhere to _interfaces_, then type-hint against those interfaces instead of specific classes.
The largest benefit of this approach is that we can very easily extend our code with support for something new without
having to modify existing code, meaning that we can reduce QA time, and the risk for negative impact to the application
is substantially reduced. We can deploy new code, faster, and with more confidence.
#### Liskov Substitution Principle
The Liskov Substitution Principle is about subtyping and inheritance. It states that “Child classes should never break
the parent class type definitions.” Or, in Robert C. Martins words, “Subtypes must be substitutable for their base
types.”
For example, if we have a `FileInterface` interface which defines an `embed()` method, and we have `Audio` and `Video`
classes which both implement the `embed()` method, then we can expect that the usage of the `embed()` method will always
do the thing that we intend. If we later create a `PDF` class or a `Gist` class which implement the `FileInterface`
interface, we will already know and understand what the `embed()` method will do. The largest benefit of this approach
is that we have the ability to build flexible and easily-configurable programs, because when we change one object of a
type (e.g., `FileInterface`) to another we don't need to change anything else in our program.
#### Interface Segregation Principle
The Interface Segregation Principle (ISP) is about _business-logic-to-clients_ communication. It states that “No client
should be forced to depend on methods it does not use.” This means that instead of having a single monolithic interface
that all conforming classes need to implement, we should instead provide a set of smaller, concept-specific interfaces
that a conforming class implements one or more of.
For example, a `Car` or `Bus` class would be interested in a `steeringWheel()` method, but a `Motorcycle` or `Tricycle`
class would not. Conversely, a `Motorcycle` or `Tricycle` class would be interested in a `handlebars()` method, but a
`Car` or `Bus` class would not. There is no need to have all of these types of vehicles implement support for both
`steeringWheel()` as well as `handlebars()`, so we should break-apart the source interface.
#### Dependency Inversion Principle
The Dependency Inversion Principle is about removing hard-links between discrete classes so that new functionality can
be leveraged by passing a different class. It states that one should *"Depend on Abstractions. Do not depend on
concretions."*. Put simply, this means our dependencies should be interfaces/contracts or abstract classes rather than
concrete implementations. We can easily refactor the above example to follow this principle.
{% highlight php %} {% highlight php %}
<?php <?php
@@ -50,12 +97,12 @@ class MysqlAdapter implements AdapterInterface {}
There are several benefits to the `Database` class now depending on an interface rather than a concretion. There are several benefits to the `Database` class now depending on an interface rather than a concretion.
Consider that you are working in a team and the adapter is being worked on by a colleague. In our first example, we Consider that we are working in a team and the adapter is being worked on by a colleague. In our first example, we
would have to wait for said colleague to finish the adapter before we could properly mock it for our unit tests. Now would have to wait for said colleague to finish the adapter before we could properly mock it for our unit tests. Now
that the dependency is an interface/contract we can happily mock that interface knowing that our colleague will build that the dependency is an interface/contract we can happily mock that interface knowing that our colleague will build
the adapter based on that contract. the adapter based on that contract.
An even bigger benefit to this method is that our code is now much more scalable. If a year down the line we decide An even bigger benefit to this method is that our code is now much more scalable. If a year down the line we decide
that we want to migrate to a different type of database, we can write an adapter that implements the original interface that we want to migrate to a different type of database, we can write an adapter that implements the original interface
and inject that instead, no more refactoring would be required as we can ensure that the adapter follows the contract and injects that instead, no more refactoring would be required as we can ensure that the adapter follows the contract
set by the interface. set by the interface.

View File

@@ -8,5 +8,5 @@ anchor: further_reading
* [Learning about Dependency Injection and PHP](http://ralphschindler.com/2011/05/18/learning-about-dependency-injection-and-php) * [Learning about Dependency Injection and PHP](http://ralphschindler.com/2011/05/18/learning-about-dependency-injection-and-php)
* [What is Dependency Injection?](http://fabien.potencier.org/article/11/what-is-dependency-injection) * [What is Dependency Injection?](http://fabien.potencier.org/article/11/what-is-dependency-injection)
* [Dependency Injection: An analogy](https://mwop.net/blog/260-Dependency-Injection-An-analogy.html) * [Dependency Injection: An analogy](https://mwop.net/blog/260-Dependency-Injection-An-analogy.html)
* [Dependency Injection: Huh?](http://net.tutsplus.com/tutorials/php/dependency-injection-huh/) * [Dependency Injection: Huh?](https://code.tutsplus.com/tutorials/dependency-injection-huh--net-26903)
* [Dependency Injection as a tool for testing](http://philipobenito.github.io/dependency-injection-as-a-tool-for-testing/) * [Dependency Injection as a tool for testing](https://medium.com/philipobenito/dependency-injection-as-a-tool-for-testing-902c21c147f1)

View File

@@ -14,6 +14,6 @@ MySQL and a little bit of MSSQL, or you need to connect to an Oracle database, t
same drivers. You'll need to learn a brand new API for each database &mdash; and that can get silly. same drivers. You'll need to learn a brand new API for each database &mdash; and that can get silly.
[mysqli]: http://php.net/mysqli [mysqli]: https://secure.php.net/mysqli
[pgsql]: http://php.net/pgsql [pgsql]: https://secure.php.net/pgsql
[mssql]: http://php.net/mssql [mssql]: https://secure.php.net/mssql

View File

@@ -6,7 +6,7 @@ anchor: mysql_extension
## MySQL Extension {#mysql_extension_title} ## MySQL Extension {#mysql_extension_title}
The [mysql] extension for PHP is incredibly old and has superseded by two other extensions: The [mysql] extension for PHP is incredibly old and has superseded by two other extensions:
- [mysqli] - [mysqli]
- [pdo] - [pdo]
@@ -14,12 +14,12 @@ The [mysql] extension for PHP is incredibly old and has superseded by two other
Not only did development stop long ago on [mysql], but it was [deprecated as of PHP 5.5.0] Not only did development stop long ago on [mysql], but it was [deprecated as of PHP 5.5.0]
[mysql_deprecated], and **has been [officially removed in PHP 7.0][mysql_removed]**. [mysql_deprecated], and **has been [officially removed in PHP 7.0][mysql_removed]**.
To save digging into your `php.ini` settings to see which module you are using, one option is to search for `mysql_*` To save digging into your `php.ini` settings to see which module you are using, one option is to search for `mysql_*`
in your editor of choice. If any functions such as `mysql_connect()` and `mysql_query()` show up, then `mysql` is in your editor of choice. If any functions such as `mysql_connect()` and `mysql_query()` show up, then `mysql` is
in use. in use.
Even if you are not using PHP 7.0 yet, failing to consider this upgrade as soon as possible will lead to greater Even if you are not using PHP 7.x yet, failing to consider this upgrade as soon as possible will lead to greater
hardship when the PHP 7.0 upgrade does come about. The best option is to replace mysql usage with [mysqli] or [PDO] in hardship when the PHP 7.x upgrade does come about. 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. your applications within your own development schedules so you won't be rushed later on.
**If you are upgrading from [mysql] to [mysqli], beware lazy upgrade guides that suggest you can simply find and replace `mysql_*` with `mysqli_*`. Not only is that a gross oversimplification, it misses out on the advantages that mysqli provides, such as parameter binding, which is also offered in [PDO][pdo].** **If you are upgrading from [mysql] to [mysqli], beware lazy upgrade guides that suggest you can simply find and replace `mysql_*` with `mysqli_*`. Not only is that a gross oversimplification, it misses out on the advantages that mysqli provides, such as parameter binding, which is also offered in [PDO][pdo].**
@@ -27,10 +27,10 @@ your applications within your own development schedules so you won't be rushed l
* [PHP: Choosing an API for MySQL][mysql_api] * [PHP: Choosing an API for MySQL][mysql_api]
* [PDO Tutorial for MySQL Developers][pdo4mysql_devs] * [PDO Tutorial for MySQL Developers][pdo4mysql_devs]
[mysql]: http://php.net/mysql [mysql]: https://secure.php.net/mysqli
[mysql_deprecated]: http://php.net/migration55.deprecated [mysql_deprecated]: https://secure.php.net/migration55.deprecated
[mysql_removed]: http://php.net/manual/en/migration70.removed-exts-sapis.php [mysql_removed]: https://secure.php.net/manual/migration70.removed-exts-sapis.php
[mysqli]: http://php.net/mysqli [mysqli]: https://secure.php.net/mysqli
[pdo]: http://php.net/pdo [pdo]: https://secure.php.net/pdo
[mysql_api]: http://php.net/mysqlinfo.api.choosing [mysql_api]: https://secure.php.net/mysqlinfo.api.choosing
[pdo4mysql_devs]: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers [pdo4mysql_devs]: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

View File

@@ -71,7 +71,7 @@ unless of course you are using persistent connections.
* [Learn about PDO connections] * [Learn about PDO connections]
[pdo]: http://php.net/pdo [pdo]: https://secure.php.net/pdo
[SQL Injection]: http://wiki.hashphp.org/Validation [SQL Injection]: http://wiki.hashphp.org/Validation
[Learn about PDO]: http://php.net/book.pdo [Learn about PDO]: https://secure.php.net/book.pdo
[Learn about PDO connections]: http://php.net/pdo.connections [Learn about PDO connections]: https://secure.php.net/pdo.connections

View File

@@ -33,7 +33,8 @@ function getAllFoos($db) {
return $db->query('SELECT * FROM table'); return $db->query('SELECT * FROM table');
} }
foreach (getAllFoos($db) as $row) { $results = getAllFoos($db);
foreach ($results as $row) {
echo "<li>".$row['field1']." - ".$row['field1']."</li>"; // BAD!! echo "<li>".$row['field1']." - ".$row['field1']."</li>"; // BAD!!
} }
{% endhighlight %} {% endhighlight %}
@@ -48,7 +49,7 @@ logic in and you have a "View", which is very nearly [MVC] - a common OOP archit
{% highlight php %} {% highlight php %}
<?php <?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password'); $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password');
// Make your model available // Make your model available
include 'models/FooModel.php'; include 'models/FooModel.php';
@@ -86,7 +87,7 @@ class FooModel
{% highlight php %} {% highlight php %}
<?php foreach ($fooList as $row): ?> <?php foreach ($fooList as $row): ?>
<?= $row['field1'] ?> - <?= $row['field1'] ?> <li><?= $row['field1'] ?> - <?= $row['field1'] ?></li>
<?php endforeach ?> <?php endforeach ?>
{% endhighlight %} {% endhighlight %}
@@ -98,6 +99,6 @@ real problem if you ever want to [unit-test](/#unit-testing) your application.
developers just getting used to the concept of interacting with databases. developers just getting used to the concept of interacting with databases.
[MVC]: http://code.tutsplus.com/tutorials/mvc-for-noobs--net-10488 [MVC]: https://code.tutsplus.com/tutorials/mvc-for-noobs--net-10488
[PHPBridge]: http://phpbridge.org/ [PHPBridge]: https://phpbridge.org/docs/
[Creating a Data Class]: http://phpbridge.org/intro-to-php/creating_a_data_class [Creating a Data Class]: https://phpbridge.org/intro-to-php/creating_a_data_class

View File

@@ -21,10 +21,10 @@ installed in any application you like:
* [Zend-db][4] * [Zend-db][4]
[1]: http://php.net/book.pdo [1]: https://secure.php.net/book.pdo
[2]: http://www.doctrine-project.org/projects/dbal.html [2]: https://www.doctrine-project.org/projects/dbal.html
[4]: https://packages.zendframework.com/docs/latest/manual/en/index.html#zendframework/zend-db [4]: https://packages.zendframework.com/docs/latest/manual/en/index.html#zendframework/zend-db
[6]: https://github.com/auraphp/Aura.Sql [6]: https://github.com/auraphp/Aura.Sql
[7]: http://propelorm.org/ [7]: http://propelorm.org/
[psr0]: http://www.php-fig.org/psr/psr-0/ [psr0]: https://www.php-fig.org/psr/psr-0/
[psr4]: http://www.php-fig.org/psr/psr-4/ [psr4]: https://www.php-fig.org/psr/psr-4/

View File

@@ -68,7 +68,7 @@ Using the [Twig] library.
[article_templating_engines]: http://fabien.potencier.org/article/34/templating-engines-in-php [article_templating_engines]: http://fabien.potencier.org/article/34/templating-engines-in-php
[Twig]: http://twig.sensiolabs.org/ [Twig]: https://twig.symfony.com/
[Brainy]: https://github.com/box/brainy [Brainy]: https://github.com/box/brainy
[Smarty]: http://www.smarty.net/ [Smarty]: https://www.smarty.net/
[Mustache]: http://mustache.github.io/ [Mustache]: https://mustache.github.io/

View File

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

View File

@@ -1,5 +1,5 @@
--- ---
isChild: true isChild: true
anchor: errors anchor: errors
--- ---
@@ -87,7 +87,8 @@ rewritten like this:
{% highlight php %} {% highlight php %}
<?php <?php
echo isset($foo['bar']) ? $foo['bar'] : ''; //Null Coalescing Operator
echo $foo['bar'] ?? '';
{% endhighlight %} {% endhighlight %}
One instance where error suppression might make sense is where `fopen()` fails to find a file to load. You could check One instance where error suppression might make sense is where `fopen()` fails to find a file to load. You could check
@@ -104,7 +105,7 @@ with the following.
xdebug.scream = On xdebug.scream = On
{% endhighlight %} {% endhighlight %}
You can also set this value at runtime with the `ini_set` function You can also set this value at runtime with the `ini_set` function
{% highlight php %} {% highlight php %}
<?php <?php
@@ -131,9 +132,11 @@ PHP is perfectly capable of being an "exception-heavy" programming language, and
make the switch. Basically you can throw your "errors" as "exceptions" using the `ErrorException` class, which extends make the switch. Basically you can throw your "errors" as "exceptions" using the `ErrorException` class, which extends
the `Exception` class. the `Exception` class.
This is a common practice implemented by a large number of modern frameworks such as Symfony and Laravel. In debug This is a common practice implemented by a large number of modern frameworks such as Symfony and Laravel. In debug
mode *(or dev mode)* both of these frameworks will display a nice and clean *stack trace*. mode *(or dev mode)* both of these frameworks will display a nice and clean *stack trace*.
There are also some packages available for better error and exception handling and reporting. Like [Whoops!], which comes with the default installation of Laravel and can be used in any framework as well.
By throwing errors as exceptions in development you can handle them better than the usual result, and if you see an By throwing errors as exceptions in development you can handle them better than the usual result, and if you see an
exception during development you can wrap it in a catch statement with specific instructions on how to handle the exception during development you can wrap it in a catch statement with specific instructions on how to handle the
situation. Each exception you catch instantly makes your application that little bit more robust. situation. Each exception you catch instantly makes your application that little bit more robust.
@@ -148,11 +151,11 @@ More information on this and details on how to use `ErrorException` with error h
[errorreport]: /#error_reporting [errorreport]: /#error_reporting
[Xdebug]: http://xdebug.org/docs/basic [Xdebug]: https://xdebug.org/docs/basic
[Scream]: http://php.net/book.scream [Scream]: https://secure.php.net/book.scream
[Error Control Operators]: http://php.net/language.operators.errorcontrol [Error Control Operators]: https://secure.php.net/language.operators.errorcontrol
[SitePoint]: http://www.sitepoint.com/ [SitePoint]: https://www.sitepoint.com/
[Whoops!]: http://filp.github.io/whoops/ [Whoops!]: https://filp.github.io/whoops/
[errorexception]: http://php.net/class.errorexception [errorexception]: https://secure.php.net/class.errorexception
[Predefined Constants for Error Handling]: http://php.net/errorfunc.constants [Predefined Constants for Error Handling]: https://secure.php.net/errorfunc.constants
[error_reporting]: http://php.net/function.error-reporting [error_reporting]: https://secure.php.net/function.error-reporting

View File

@@ -71,7 +71,7 @@ standard Exception which is vague, or creating a custom Exception just for that,
[splext]: /#standard_php_library [splext]: /#standard_php_library
[exceptions]: http://php.net/language.exceptions [exceptions]: https://secure.php.net/language.exceptions
[splexe]: http://php.net/spl.exceptions [splexe]: https://secure.php.net/spl.exceptions
[nesting-exceptions-in-php]: http://www.brandonsavage.net/exceptional-php-nesting-exceptions-in-php/ [nesting-exceptions-in-php]: https://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 [exception-best-practices53]: http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3

View File

@@ -3,3 +3,6 @@ anchor: security
--- ---
# Security {#security_title} # Security {#security_title}
The best resource I've found on PHP security is [The 2018 Guide to Building Secure PHP Software](https://paragonie.com/blog/2017/12/2018-guide-building-secure-php-software) by
[Paragon Initiative](https://paragonie.com/).

View File

@@ -5,6 +5,25 @@ anchor: web_application_security
## Web Application Security {#web_application_security_title} ## Web Application Security {#web_application_security_title}
It is very important for every PHP developer to learn [the basics of web application security][4], which can be broken
down into a handful of broad topics:
1. Code-data separation.
* When data is executed as code, you get SQL Injection, Cross-Site Scripting, Local/Remote File Inclusion, etc.
* When code is printed as data, you get information leaks (source code disclosure or, in the case of C programs,
enough information to bypass [ASLR][5]).
2. Application logic.
* Missing authentication or authorization controls.
* Input validation.
3. Operating environment.
* PHP versions.
* Third party libraries.
* The operating system.
4. Cryptography weaknesses.
* [Weak random numbers][6].
* [Chosen-ciphertext attacks][7].
* [Side-channel information leaks][8].
There are bad people ready and willing to exploit your web application. It is important that you take necessary 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 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 [The Open Web Application Security Project][1] (OWASP) have compiled a comprehensive list of known security issues and
@@ -15,4 +34,10 @@ methods to protect yourself against them. This is a must read for the security-c
[1]: https://www.owasp.org/ [1]: https://www.owasp.org/
[2]: https://www.owasp.org/index.php/Guide_Table_of_Contents [2]: https://www.owasp.org/index.php/Guide_Table_of_Contents
[3]: http://phpsecurity.readthedocs.org/en/latest/index.html [3]: https://phpsecurity.readthedocs.io/en/latest/index.html
[4]: https://paragonie.com/blog/2015/08/gentle-introduction-application-security
[5]: http://searchsecurity.techtarget.com/definition/address-space-layout-randomization-ASLR
[6]: https://paragonie.com/blog/2016/01/on-design-and-implementation-stealth-backdoor-for-web-applications
[7]: https://paragonie.com/blog/2015/05/using-encryption-and-authentication-correctly
[8]: http://blog.ircmaxell.com/2014/11/its-all-about-time.html

View File

@@ -8,17 +8,31 @@ anchor: password_hashing
Eventually everyone builds a PHP application that relies on user login. Usernames and passwords are stored in a 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. 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, It is important that you properly [_hash_][3] passwords before storing them. Hashing and encrypting are [two very different things][7]
one-way function performed against the user's password. This produces a fixed-length string that cannot be feasibly that often get confused.
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 Hashing is an irreversible, one-way function. This produces a fixed-length string that cannot be feasibly reversed.
unauthorized third-party, all user accounts are now compromised. 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.
Unlike hashing, encryption is reversible (provided you have the key). Encryption is useful in other areas, but is a poor
strategy for securely storing passwords.
Passwords should also be individually [_salted_][5] by adding a random string to each password before hashing. This prevents dictionary attacks and the use of "rainbow tables" (a reverse list of crytographic hashes for common passwords.) Passwords should also be individually [_salted_][5] by adding a random string to each password before hashing. This prevents dictionary attacks and the use of "rainbow tables" (a reverse list of crytographic hashes for common passwords.)
Hashing and salting are vital as often users use the same password for multiple services and password quality can be poor. Hashing and salting are vital as often users use the same password for multiple services and password quality can be poor.
Fortunately, nowadays PHP makes this easy. Additionally, you should use [a specialized _password hashing_ algoithm][6] rather than fast, general-purpose
cryptographic hash function (e.g. SHA256). The short list of acceptable password hashing algorithms (as of June 2018)
to use are:
* Argon2 (available in PHP 7.2 and newer)
* Scrypt
* **Bcrypt** (PHP provides this one for you; see below)
* PBKDF2 with HMAC-SHA256 or HMAC-SHA512
Fortunately, nowadays PHP makes this easy.
**Hashing passwords with `password_hash`** **Hashing passwords with `password_hash`**
@@ -40,9 +54,9 @@ if (password_verify('bad-password', $passwordHash)) {
} else { } else {
// Wrong password // Wrong password
} }
{% endhighlight %} {% endhighlight %}
`password_hash()` takes care of password salting for you. The salt is stored, along with the algorithm and "cost", as part of the hash. `password_verify()` extracts this to determine how to check the password, so you don't need a separate database field to store your salts. `password_hash()` takes care of password salting for you. The salt is stored, along with the algorithm and "cost", as part of the hash. `password_verify()` extracts this to determine how to check the password, so you don't need a separate database field to store your salts.
* [Learn about `password_hash()`] [1] * [Learn about `password_hash()`] [1]
* [`password_compat` for PHP >= 5.3.7 && < 5.5] [2] * [`password_compat` for PHP >= 5.3.7 && < 5.5] [2]
@@ -51,8 +65,11 @@ if (password_verify('bad-password', $passwordHash)) {
* [PHP `password_hash()` RFC] [4] * [PHP `password_hash()` RFC] [4]
[1]: http://php.net/function.password-hash [1]: https://secure.php.net/function.password-hash
[2]: https://github.com/ircmaxell/password_compat [2]: https://github.com/ircmaxell/password_compat
[3]: http://en.wikipedia.org/wiki/Cryptographic_hash_function [3]: https://wikipedia.org/wiki/Cryptographic_hash_function
[4]: https://wiki.php.net/rfc/password_hash [4]: https://wiki.php.net/rfc/password_hash
[5]: https://en.wikipedia.org/wiki/Salt_(cryptography) [5]: https://wikipedia.org/wiki/Salt_(cryptography)
[6]: https://paragonie.com/blog/2016/02/how-safely-store-password-in-2016
[7]: https://paragonie.com/blog/2015/08/you-wouldnt-base64-a-password-cryptography-decoded

View File

@@ -62,11 +62,11 @@ phone number, or age when processing a registration submission.
[See Validation Filters][3] [See Validation Filters][3]
[1]: http://php.net/book.filter [1]: https://secure.php.net/book.filter
[2]: http://php.net/filter.filters.sanitize [2]: https://secure.php.net/filter.filters.sanitize
[3]: http://php.net/filter.filters.validate [3]: https://secure.php.net/filter.filters.validate
[4]: http://php.net/function.filter-var [4]: https://secure.php.net/function.filter-var
[5]: http://php.net/function.filter-input [5]: https://secure.php.net/function.filter-input
[6]: http://php.net/security.filesystem.nullbytes [6]: https://secure.php.net/security.filesystem.nullbytes
[html-purifier]: http://htmlpurifier.org/ [html-purifier]: http://htmlpurifier.org/
[unserialize]: https://secure.php.net/manual/en/function.unserialize.php [unserialize]: https://secure.php.net/manual/function.unserialize.php

View File

@@ -15,4 +15,4 @@ issues as your application cannot effectively tell where the data is coming from
For example: `$_GET['foo']` would be available via `$foo`, which can override variables that have not been declared. For example: `$_GET['foo']` would be available via `$foo`, which can override variables that have not been declared.
If you are using PHP < 5.4.0 __make sure__ that `register_globals` is __off__. If you are using PHP < 5.4.0 __make sure__ that `register_globals` is __off__.
* [Register_globals in the PHP manual](http://php.net/security.globals) * [Register_globals in the PHP manual](https://secure.php.net/security.globals)

View File

@@ -23,7 +23,7 @@ log_errors = On
> Passing in the value `-1` will show every possible error, even when new levels and constants are added in future 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. - > versions. The `E_ALL` constant also behaves this way as of PHP 5.4. -
> [php.net](http://php.net/function.error-reporting) > [php.net](https://secure.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 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 `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
@@ -49,7 +49,7 @@ log_errors = On
With these settings in production, errors will still be logged to the error logs for the web server, but will not be With these settings in production, errors will still be logged to the error logs for the web server, but will not be
shown to the user. For more information on these settings, see the PHP manual: shown to the user. For more information on these settings, see the PHP manual:
* [error_reporting](http://php.net/errorfunc.configuration#ini.error-reporting) * [error_reporting](https://secure.php.net/errorfunc.configuration#ini.error-reporting)
* [display_errors](http://php.net/errorfunc.configuration#ini.display-errors) * [display_errors](https://secure.php.net/errorfunc.configuration#ini.display-errors)
* [display_startup_errors](http://php.net/errorfunc.configuration#ini.display-startup-errors) * [display_startup_errors](https://secure.php.net/errorfunc.configuration#ini.display-startup-errors)
* [log_errors](http://php.net/errorfunc.configuration#ini.log-errors) * [log_errors](https://secure.php.net/errorfunc.configuration#ini.log-errors)

View File

@@ -5,7 +5,7 @@ anchor: test_driven_development
## Test Driven Development {#test_driven_development_title} ## Test Driven Development {#test_driven_development_title}
From [Wikipedia](http://en.wikipedia.org/wiki/Test-driven_development): From [Wikipedia](https://wikipedia.org/wiki/Test-driven_development):
> Test-driven development (TDD) is a software development process that relies on the repetition of a very short > 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 > development cycle: first the developer writes a failing automated test case that defines a desired improvement or new
@@ -32,17 +32,17 @@ The other use for unit tests is contributing to open source. If you can write a
(i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If you run a project (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. 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 [PHPUnit](https://phpunit.de/) is the de-facto testing framework for writing unit tests for PHP applications, but there
are several alternatives are several alternatives
* [atoum](https://github.com/atoum/atoum) * [atoum](https://github.com/atoum/atoum)
* [Kahlan](https://github.com/crysalead/kahlan) * [Kahlan](https://github.com/crysalead/kahlan)
* [Peridot](http://peridot-php.github.io/) * [Peridot](https://peridot-php.github.io/)
* [SimpleTest](http://simpletest.org) * [SimpleTest](http://simpletest.org)
### Integration Testing ### Integration Testing
From [Wikipedia](http://en.wikipedia.org/wiki/Integration_testing): From [Wikipedia](https://wikipedia.org/wiki/Integration_testing):
> Integration testing (sometimes called Integration and Testing, abbreviated "I&T") is the phase in software testing in > 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 > which individual software modules are combined and tested as a group. It occurs after unit testing and before
@@ -62,7 +62,7 @@ users of the application.
#### Functional Testing Tools #### Functional Testing Tools
* [Selenium](http://seleniumhq.com) * [Selenium](https://docs.seleniumhq.org/)
* [Mink](http://mink.behat.org) * [Mink](http://mink.behat.org/)
* [Codeception](http://codeception.com) is a full-stack testing framework that includes acceptance testing tools * [Codeception](https://codeception.com/) is a full-stack testing framework that includes acceptance testing tools
* [Storyplayer](http://datasift.github.io/storyplayer) is a full-stack testing framework that includes support for creating and destroying test environments on demand * [Storyplayer](https://datasift.github.io/storyplayer/) is a full-stack testing framework that includes support for creating and destroying test environments on demand

View File

@@ -25,7 +25,7 @@ purpose. This framework is inspired by the [RSpec project][Rspec] for Ruby.
[Behat]: http://behat.org/ [Behat]: http://behat.org/
[Cucumber]: http://cukes.info/ [Cucumber]: https://cucumber.io/
[PHPSpec]: http://www.phpspec.net/ [PHPSpec]: https://www.phpspec.net/
[RSpec]: http://rspec.info/ [RSpec]: https://rspec.info/
[Codeception]: http://codeception.com/ [Codeception]: https://codeception.com/

View File

@@ -14,11 +14,16 @@ libraries useful for any preferred approach taken.
* [Mockery] is a Mock Object Framework which can be integrated with [PHPUnit] or [PHPSpec] * [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 * [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]. [PHPSpec] and can be used with [PHPUnit].
* [php-mock] is a library to help to mock PHP native functions.
* [Infection] is a PHP implementation of [Mutation Testing] to help to measure the effectiveness of your tests.
[Selenium]: http://seleniumhq.org/ [Selenium]: https://www.seleniumhq.org/
[integrated with PHPUnit]: https://github.com/giorgiosironi/phpunit-selenium/ [integrated with PHPUnit]: https://github.com/giorgiosironi/phpunit-selenium/
[Mockery]: https://github.com/padraic/mockery [Mockery]: https://github.com/padraic/mockery
[PHPUnit]: http://phpunit.de/ [PHPUnit]: https://phpunit.de/
[PHPSpec]: http://www.phpspec.net/ [PHPSpec]: https://www.phpspec.net/
[Prophecy]: https://github.com/phpspec/prophecy [Prophecy]: https://github.com/phpspec/prophecy
[php-mock]: https://github.com/php-mock/php-mock
[Infection]: https://github.com/infection/infection
[Mutation Testing]: https://en.wikipedia.org/wiki/Mutation_testing

View File

@@ -21,7 +21,7 @@ especially important on virtual servers that don't have much memory to spare.
### Apache and PHP ### Apache and PHP
PHP and Apache have a long history together. Apache is wildly configurable and has many available 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 [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 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. cannot handle as many visitors at the same time.
@@ -45,16 +45,16 @@ If you are running Apache 2.4 or later, you can use [mod_proxy_fcgi] to get grea
* [Read more on setting up Apache and PHP-FPM with mod_proxy_fcgi][tutorial-mod_proxy_fcgi] * [Read more on setting up Apache and PHP-FPM with mod_proxy_fcgi][tutorial-mod_proxy_fcgi]
[nginx]: http://nginx.org/ [nginx]: https://nginx.org/
[phpfpm]: http://php.net/install.fpm [phpfpm]: https://secure.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/ [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/ [apache-modules]: https://httpd.apache.org/docs/2.4/mod/
[prefork MPM]: http://httpd.apache.org/docs/2.4/mod/prefork.html [prefork MPM]: https://httpd.apache.org/docs/2.4/mod/prefork.html
[worker MPM]: http://httpd.apache.org/docs/2.4/mod/worker.html [worker MPM]: https://httpd.apache.org/docs/2.4/mod/worker.html
[event MPM]: http://httpd.apache.org/docs/2.4/mod/event.html [event MPM]: https://httpd.apache.org/docs/2.4/mod/event.html
[apache]: http://httpd.apache.org/ [apache]: https://httpd.apache.org/
[apache-MPM]: http://httpd.apache.org/docs/2.4/mod/mpm_common.html [apache-MPM]: https://httpd.apache.org/docs/2.4/mod/mpm_common.html
[mod_fastcgi]: https://blogs.oracle.com/opal/entry/php_fpm_fastcgi_process_manager [mod_fastcgi]: https://blogs.oracle.com/opal/entry/php_fpm_fastcgi_process_manager
[mod_fcgid]: http://httpd.apache.org/mod_fcgid/ [mod_fcgid]: hhttps://httpd.apache.org/mod_fcgid/
[mod_proxy_fcgi]: https://httpd.apache.org/docs/current/mod/mod_proxy_fcgi.html [mod_proxy_fcgi]: https://httpd.apache.org/docs/current/mod/mod_proxy_fcgi.html
[tutorial-mod_proxy_fcgi]: https://serversforhackers.com/video/apache-and-php-fpm [tutorial-mod_proxy_fcgi]: https://serversforhackers.com/video/apache-and-php-fpm

View File

@@ -28,7 +28,7 @@ There are many open source tools available to help you with build automation and
[Phing] can control your packaging, deployment or testing process from within a XML build file. Phing (which is based on [Apache Ant]) provides a rich set of tasks usually needed to install or update a web application and can be extended with additional custom tasks, written in PHP. It's a solid and robust tool and has been around for a long time, however the tool could be perceived as a bit old fashioned because of the way it deals with configuration (XML files). [Phing] can control your packaging, deployment or testing process from within a XML build file. Phing (which is based on [Apache Ant]) provides a rich set of tasks usually needed to install or update a web application and can be extended with additional custom tasks, written in PHP. It's a solid and robust tool and has been around for a long time, however the tool could be perceived as a bit old fashioned because of the way it deals with configuration (XML files).
[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 you can successfully deploy 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][phpdeploy_capistrano] is a good starting point for PHP developers interested in Capistrano. [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 you can successfully deploy PHP systems with it. Successful use of Capistrano depends on a working knowledge of Ruby and Rake.
[Ansistrano] is a couple of Ansible roles to easily manage the deployment process (deploy and rollback) for scripting applications such as PHP, Python and Ruby. It's an Ansible port for [Capistrano]. It's been used by quite a lot of PHP companies already. [Ansistrano] is a couple of Ansible roles to easily manage the deployment process (deploy and rollback) for scripting applications such as PHP, Python and Ruby. It's an Ansible port for [Capistrano]. It's been used by quite a lot of PHP companies already.
@@ -41,7 +41,6 @@ There are many open source tools available to help you with build automation and
#### Further reading: #### Further reading:
* [Automate your project with Apache Ant][apache_ant_tutorial] * [Automate your project with Apache Ant][apache_ant_tutorial]
* [Expert PHP Deployments][expert_php_deployments] - free book on deployment with Capistrano, Phing and Vagrant.
* [Deploying PHP Applications][deploying_php_applications] - paid book on best practices and tools for PHP deployment. * [Deploying PHP Applications][deploying_php_applications] - paid book on best practices and tools for PHP deployment.
### Server Provisioning ### Server Provisioning
@@ -50,7 +49,7 @@ Managing and configuring servers can be a daunting task when faced with many ser
[Ansible] is a tool that manages your infrastructure through YAML files. It's simple to get started with and can manage complex and large scale applications. There is an API for managing cloud instances and it can manage them through a dynamic inventory using certain tools. [Ansible] is a tool that manages your infrastructure through YAML files. It's simple to get started with and can manage complex and large scale applications. There is an API for managing cloud instances and it can manage them through a dynamic inventory using certain tools.
[Puppet] is a tool that has its own language and file types for managing servers and configurations. It can be used in a master/client setup or it can be used in a "master-less" mode. In the master/client mode the clients will poll the central master(s) for new configuration on set intervals and update itself if necessary. In the master-less mode you can push changes to your nodes. [Puppet] is a tool that has its own language and file types for managing servers and configurations. It can be used in a master/client setup or it can be used in a "master-less" mode. In the master/client mode the clients will poll the central master(s) for new configuration on set intervals and update itself if necessary. In the master-less mode you can push changes to your nodes.
[Chef] is a powerful Ruby based system integration framework that you can build your whole server environment or virtual boxes with. It integrates well with Amazon Web Services through their service called OpsWorks. [Chef] is a powerful Ruby based system integration framework that you can build your whole server environment or virtual boxes with. It integrates well with Amazon Web Services through their service called OpsWorks.
@@ -83,28 +82,25 @@ PHP.
* [Continuous Integration with PHPCI][PHPCI] * [Continuous Integration with PHPCI][PHPCI]
* [Continuous Integration with Teamcity][Teamcity] * [Continuous Integration with Teamcity][Teamcity]
[buildautomation]: https://wikipedia.org/wiki/Build_automation
[buildautomation]: http://en.wikipedia.org/wiki/Build_automation [Phing]: https://www.phing.info/
[Phing]: http://www.phing.info/ [Apache Ant]: https://ant.apache.org/
[Apache Ant]: http://ant.apache.org/ [Capistrano]: http://capistranorb.com/
[Capistrano]: https://github.com/capistrano/capistrano/wiki [Ansistrano]: https://ansistrano.com
[Ansistrano]: http://ansistrano.com [phpdeploy_deployer]: https://www.sitepoint.com/deploying-php-applications-with-deployer/
[phpdeploy_capistrano]: http://www.davegardner.me.uk/blog/2012/02/13/php-deployment-with-capistrano/
[phpdeploy_deployer]: http://www.sitepoint.com/deploying-php-applications-with-deployer/
[Chef]: https://www.chef.io/ [Chef]: https://www.chef.io/
[chef_vagrant_and_ec2]: http://www.jasongrimes.org/2012/06/managing-lamp-environments-with-chef-vagrant-and-ec2-1-of-3/ [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/chef-cookbooks/php [Chef_cookbook]: https://github.com/chef-cookbooks/php
[Chef_tutorial]: https://www.youtube.com/playlist?list=PL11cZfNdwNyPnZA9D1MbVqldGuOWqbumZ [Chef_tutorial]: https://www.youtube.com/playlist?list=PL11cZfNdwNyPnZA9D1MbVqldGuOWqbumZ
[apache_ant_tutorial]: http://net.tutsplus.com/tutorials/other/automate-your-projects-with-apache-ant/ [apache_ant_tutorial]: https://code.tutsplus.com/tutorials/automate-your-projects-with-apache-ant--net-18595
[Travis CI]: https://travis-ci.org/ [Travis CI]: https://travis-ci.org/
[Jenkins]: http://jenkins-ci.org/ [Jenkins]: https://jenkins.io/
[PHPCI]: http://www.phptesting.org/ [PHPCI]: https://www.phptesting.org/
[Teamcity]: http://www.jetbrains.com/teamcity/ [Teamcity]: https://www.jetbrains.com/teamcity/
[Deployer]: http://deployer.org/ [Deployer]: https://deployer.org/
[Rocketeer]: http://rocketeer.autopergamene.eu/ [Rocketeer]: http://rocketeer.autopergamene.eu/
[Magallanes]: http://magephp.com/ [Magallanes]: https://www.magephp.com/
[expert_php_deployments]: http://viccherubini.com/assets/Expert-PHP-Deployments.pdf [deploying_php_applications]: https://deployingphpapplications.com/
[deploying_php_applications]: http://www.deployingphpapplications.com
[Ansible]: https://www.ansible.com/ [Ansible]: https://www.ansible.com/
[Puppet]: https://puppet.com/ [Puppet]: https://puppet.com/
[ansible_for_devops]: https://leanpub.com/ansible-for-devops [ansible_for_devops]: https://leanpub.com/ansible-for-devops

View File

@@ -28,10 +28,10 @@ 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. - [Phansible][Phansible]: provides an easy to use interface that helps you generate Ansible Playbooks for PHP based projects.
[Vagrant]: http://vagrantup.com/ [Vagrant]: https://www.vagrantup.com/
[Puppet]: http://www.puppetlabs.com/ [Puppet]: https://puppet.com/
[Chef]: https://www.chef.io/ [Chef]: https://www.chef.io/
[Rove]: http://rove.io/ [Rove]: http://rove.io/
[Puphpet]: https://puphpet.com/ [Puphpet]: https://puphpet.com/
[Protobox]: http://getprotobox.com/ [Protobox]: https://www.getprotobox.com/
[Phansible]: http://phansible.com/ [Phansible]: http://phansible.com/

View File

@@ -11,7 +11,7 @@ A typical LAMP application might have three containers: a web server, a PHP-FPM
You can generate containers from the command line (see example below) or, for ease of maintenance, build a `docker-compose.yml` file for your project specifying which to create and how they communicate with one another. You can generate containers from the command line (see example below) or, for ease of maintenance, build a `docker-compose.yml` file for your project specifying which to create and how they communicate with one another.
Docker may help if you're developing multiple websites and want the separation that comes from installing each on it's own virtual machine, but don't have the necessary disk space or the time to keep everything up to date. It's efficient: the installation and downloads are quicker, you only need to store one copy of each image however often it's used, containers need less RAM and share the same OS kernel, so you can have more servers running simultaneously, and it takes a matter of seconds to stop and start them, no need to wait for a full server boot. Docker may help if you're developing multiple websites and want the separation that comes from installing each on it's own virtual machine, but don't have the necessary disk space or the time to keep everything up to date. It's efficient: the installation and downloads are quicker, you only need to store one copy of each image however often it's used, containers need less RAM and share the same OS kernel, so you can have more servers running simultaneously, and it takes a matter of seconds to stop and start them, no need to wait for a full server boot.
### Example: Running your PHP Applications in Docker ### Example: Running your PHP Applications in Docker
@@ -36,9 +36,9 @@ The [PHPDocker.io] site will auto-generate all the files you need for a fully-fe
* [Docker Hub][docker-hub] * [Docker Hub][docker-hub]
* [Docker Hub - official images][docker-hub-official] * [Docker Hub - official images][docker-hub-official]
[Docker]: http://docker.com/ [Docker]: https://www.docker.com/
[docker-hub]: https://hub.docker.com/ [docker-hub]: https://hub.docker.com/
[docker-hub-official]: https://hub.docker.com/explore/ [docker-hub-official]: https://hub.docker.com/explore/
[docker-install]: https://docs.docker.com/installation/ [docker-install]: https://docs.docker.com/install/
[docker-doc]: https://docs.docker.com/userguide/ [docker-doc]: https://docs.docker.com/
[PHPDocker.io]: https://phpdocker.io/generator [PHPDocker.io]: https://phpdocker.io/generator

View File

@@ -5,11 +5,11 @@ anchor: opcode_cache
## Opcode Cache {#opcode_cache_title} ## Opcode Cache {#opcode_cache_title}
When a PHP file is executed, it must first be compiled into [opcodes](http://php.net/manual/en/internals2.opcodes.php) (machine language instructions for the CPU). If the source code is unchanged, the opcodes will be the same, so this compilation step becomes a waste of CPU resources. When a PHP file is executed, it must first be compiled into [opcodes](https://secure.php.net/manual/internals2.opcodes.php) (machine language instructions for the CPU). If the source code is unchanged, the opcodes will be the same, so this compilation step becomes a waste of CPU resources.
An opcode cache prevents redundant compilation by storing opcodes in memory and reusing them on successive calls. It will typically check signature or modification time of the file first, in case there have been any changes. An opcode cache prevents redundant compilation by storing opcodes in memory and reusing them on successive calls. It will typically check signature or modification time of the file first, in case there have been any changes.
It's likely an opcode cache will make a significant speed improvement to your application. Since PHP 5.5 there is one built in - [Zend OPcache][opcache-book]. Depending on your PHP package/distribution, it's usually turned on by default - check [opcache.enable](http://php.net/manual/en/opcache.configuration.php#ini.opcache.enable) and the output of `phpinfo()` to make sure. For earlier versions there's a PECL extension. It's likely an opcode cache will make a significant speed improvement to your application. Since PHP 5.5 there is one built in - [Zend OPcache][opcache-book]. Depending on your PHP package/distribution, it's usually turned on by default - check [opcache.enable](https://secure.php.net/manual/opcache.configuration.php#ini.opcache.enable) and the output of `phpinfo()` to make sure. For earlier versions there's a PECL extension.
Read more about opcode caches: Read more about opcode caches:
@@ -21,9 +21,9 @@ Read more about opcode caches:
* [list of PHP accelerators on Wikipedia][PHP_accelerators] * [list of PHP accelerators on Wikipedia][PHP_accelerators]
[opcache-book]: http://php.net/book.opcache [opcache-book]: https://secure.php.net/book.opcache
[APC]: http://php.net/book.apc [APC]: https://secure.php.net/book.apc
[XCache]: http://xcache.lighttpd.net/ [XCache]: https://xcache.lighttpd.net/
[Zend Optimizer+]: https://github.com/zendtech/ZendOptimizerPlus [Zend Optimizer+]: https://github.com/zendtech/ZendOptimizerPlus
[WinCache]: http://www.iis.net/download/wincacheforphp [WinCache]: https://www.iis.net/downloads/microsoft/wincache-extension
[PHP_accelerators]: http://en.wikipedia.org/wiki/List_of_PHP_accelerators [PHP_accelerators]: https://wikipedia.org/wiki/List_of_PHP_accelerators

View File

@@ -48,8 +48,8 @@ object cache to PHP 5.5+, since PHP now has a built-in bytecode cache (OPcache).
### Learn more about popular object caching systems: ### Learn more about popular object caching systems:
* [APCu](https://github.com/krakjoe/apcu) * [APCu](https://github.com/krakjoe/apcu)
* [APC Functions](http://php.net/ref.apc) * [APC Functions](https://secure.php.net/ref.apc)
* [Memcached](http://memcached.org/) * [Memcached](https://memcached.org/)
* [Redis](http://redis.io/) * [Redis](https://redis.io/)
* [XCache APIs](http://xcache.lighttpd.net/wiki/XcacheApi) * [XCache APIs](https://xcache.lighttpd.net/wiki/XcacheApi)
* [WinCache Functions](http://php.net/ref.wincache) * [WinCache Functions](https://secure.php.net/ref.wincache)

View File

@@ -70,10 +70,10 @@ difference between the second and third methods' doc block is the inclusion/excl
`@return void` explicitly informs us that there is no return; historically omitting the `@return void` statement also results in the same (no return) action. `@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 [tags]: https://docs.phpdoc.org/references/phpdoc/tags/index.html
[PHPDoc manual]: http://www.phpdoc.org/docs/latest/index.html [PHPDoc manual]: https://docs.phpdoc.org/index.html
[@author]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/author.html [@author]: https://docs.phpdoc.org/references/phpdoc/tags/author.html
[@link]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/link.html [@link]: https://docs.phpdoc.org/references/phpdoc/tags/link.html
[@param]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/param.html [@param]: https://docs.phpdoc.org/references/phpdoc/tags/param.html
[@return]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/return.html [@return]: https://docs.phpdoc.org/references/phpdoc/tags/return.html
[@throws]: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/throws.html [@throws]: https://docs.phpdoc.org/references/phpdoc/tags/throws.html

View File

@@ -6,5 +6,5 @@ anchor: from_the_source
## From the Source {#from_the_source_title} ## From the Source {#from_the_source_title}
* [PHP Website](http://php.net/) * [PHP Website](https://secure.php.net/)
* [PHP Documentation](http://php.net/docs.php) * [PHP Documentation](https://secure.php.net/docs.php)

View File

@@ -8,10 +8,7 @@ anchor: people_to_follow
It's difficult to find interesting and knowledgeable PHP It's difficult to find interesting and knowledgeable PHP
community members when you are first starting out. You can community members when you are first starting out. You can
find a comprehensive list of PHP community members and their find an abbreviated list of PHP community members to get you started at:
Twitter handles at:
* [25 PHP Developers to Follow Online][php-developers-to-follow] * <https://www.ogprogrammer.com/2017/06/28/how-to-get-connected-with-the-php-community/>
* <https://twitter.com/CalEvans/lists/phpeople>
[php-developers-to-follow]: https://blog.newrelic.com/2014/05/02/25-php-developers-follow-online/

View File

@@ -5,4 +5,4 @@ anchor: mentoring
## Mentoring {#mentoring_title} ## Mentoring {#mentoring_title}
* [php-mentoring.org](http://php-mentoring.org/) - Formal, peer to peer mentoring in the PHP community. * [php-mentoring.org](https://php-mentoring.org/) - Formal, peer to peer mentoring in the PHP community.

View File

@@ -6,19 +6,19 @@ anchor: php_paas_providers
## PHP PaaS Providers {#php_paas_providers_title} ## PHP PaaS Providers {#php_paas_providers_title}
* [PagodaBox](https://pagodabox.io/)
* [AppFog](https://www.ctl.io/appfog/) * [AppFog](https://www.ctl.io/appfog/)
* [Heroku](https://devcenter.heroku.com/categories/php)
* [fortrabbit](https://www.fortrabbit.com/)
* [Engine Yard Cloud](https://www.engineyard.com/features)
* [Red Hat OpenShift Platform](https://www.openshift.com/)
* [AWS Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/) * [AWS Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/)
* [Windows Azure](http://www.windowsazure.com/) * [Cloudways](https://www.cloudways.com/)
* [Engine Yard Cloud](https://www.engineyard.com/features)
* [fortrabbit](https://www.fortrabbit.com/)
* [Google App Engine](https://cloud.google.com/appengine/docs/php/) * [Google App Engine](https://cloud.google.com/appengine/docs/php/)
* [Jelastic](http://jelastic.com/) * [Heroku](https://devcenter.heroku.com/categories/php-support)
* [IBM Cloud](https://console.bluemix.net/docs/runtimes/php/getting-started.html#getting_started)
* [Jelastic](https://jelastic.com/)
* [Microsoft Azure](https://azure.microsoft.com/)
* [Nanobox](https://nanobox.io/)
* [Pivotal Web Services](https://run.pivotal.io/)
* [Platform.sh](https://platform.sh/) * [Platform.sh](https://platform.sh/)
* [Cloudways](https://www.cloudways.com/en/) * [Red Hat OpenShift](https://www.openshift.com/)
* [IBM Bluemix Cloud Foundry](https://console.ng.bluemix.net/)
* [Pivotal Web Service Cloud Foundry](https://run.pivotal.io/)
To see which versions these PaaS hosts are running, head over to [PHP Versions](http://phpversions.info/paas-hosting/). To see which versions these PaaS hosts are running, head over to [PHP Versions](http://phpversions.info/paas-hosting/).

View File

@@ -19,10 +19,8 @@ Micro-frameworks are essentially a wrapper to route a HTTP request to a callback
possible, and sometimes come with a few extra libraries to assist development such as basic database wrappers and the 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. 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 Many frameworks add a considerable number of features on top of what is available in a micro-framework; these are
known Full-Stack Frameworks. These often come bundled with ORMs, Authentication packages, etc. called 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 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. frameworks can be used together to make a micro- or full-stack framework.
* [Popular PHP Frameworks](https://github.com/codeguy/php-the-right-way/wiki/Frameworks)

View File

@@ -20,9 +20,15 @@ another source of packages which ideally have little to no dependencies on other
For example, you can use the [FuelPHP Validation package], without needing to use the FuelPHP framework itself. For example, you can use the [FuelPHP Validation package], without needing to use the FuelPHP framework itself.
* [Aura] * [Aura]
* CakePHP Components
* [Collection]
* [Database]
* [Datasource]
* [Event]
* [I18n]
* [ORM]
* [FuelPHP] * [FuelPHP]
* [Hoa Project] * [Hoa Project]
* [Orno]
* [Symfony Components] * [Symfony Components]
* [The League of Extraordinary Packages] * [The League of Extraordinary Packages]
* Laravel's Illuminate Components * Laravel's Illuminate Components
@@ -38,13 +44,18 @@ components best decoupled from the Laravel framework are listed above._
[PEAR]: /#pear [PEAR]: /#pear
[Dependency Management]: /#dependency_management [Dependency Management]: /#dependency_management
[FuelPHP Validation package]: https://github.com/fuelphp/validation [FuelPHP Validation package]: https://github.com/fuelphp/validation
[Aura]: http://auraphp.com/framework/2.x/en/ [Aura]: http://auraphp.com/framework/
[FuelPHP]: https://github.com/fuelphp [FuelPHP]: https://github.com/fuelphp
[Hoa Project]: https://github.com/hoaproject [Hoa Project]: https://github.com/hoaproject
[Orno]: https://github.com/orno [Symfony Components]: https://symfony.com/doc/current/components/index.html
[Symfony Components]: http://symfony.com/doc/current/components/index.html [The League of Extraordinary Packages]: https://thephpleague.com/
[The League of Extraordinary Packages]: http://thephpleague.com/
[IoC Container]: https://github.com/illuminate/container [IoC Container]: https://github.com/illuminate/container
[Eloquent ORM]: https://github.com/illuminate/database [Eloquent ORM]: https://github.com/illuminate/database
[Queue]: https://github.com/illuminate/queue [Queue]: https://github.com/illuminate/queue
[Illuminate components]: https://github.com/illuminate [Illuminate components]: https://github.com/illuminate
[Collection]: https://github.com/cakephp/collection
[Database]: https://github.com/cakephp/database
[Datasource]: https://github.com/cakephp/datasource
[Event]: https://github.com/cakephp/event
[I18n]: https://github.com/cakephp/i18n
[ORM]: https://github.com/cakephp/orm

View File

@@ -16,18 +16,20 @@ PHP versions
* [PHP Best Practices](https://phpbestpractices.org/) * [PHP Best Practices](https://phpbestpractices.org/)
* [Best practices for Modern PHP Development](https://www.airpair.com/php/posts/best-practices-for-modern-php-development) * [Best practices for Modern PHP Development](https://www.airpair.com/php/posts/best-practices-for-modern-php-development)
* [Why You Should Be Using Supported PHP Versions](https://kinsta.com/blog/php-versions/)
### News around the PHP and web development communities ### News around the PHP and web development communities
You can subscribe to weekly newsletters to keep yourself informed on new libraries, latest news, events and general You can subscribe to weekly newsletters to keep yourself informed on new libraries, latest news, events and general
announcements, as well as additional resources being published every now and then: announcements, as well as additional resources being published every now and then:
* [PHP Weekly](http://www.phpweekly.com) * [PHP Weekly](http://www.phpweekly.com)
* [JavaScript Weekly](http://javascriptweekly.com) * [JavaScript Weekly](https://javascriptweekly.com/)
* [HTML5 Weekly](http://html5weekly.com) * [Frontend Focus](https://frontendfoc.us/)
* [Mobile Web Weekly](http://mobilewebweekly.co) * [Mobile Web Weekly](https://mobiledevweekly.com/)
* There are also Weeklies on other platforms you might be interested in; here's
[a list of some](https://github.com/jondot/awesome-weekly). There are also Weeklies on other platforms you might be interested in; here's [a list of some](https://github.com/jondot/awesome-weekly).
### PHP universe ### PHP universe
* [PHP Developer blog](http://blog.phpdeveloper.org/) * [PHP Developer blog](https://blog.phpdeveloper.org/)

View File

@@ -14,8 +14,8 @@ title: Video Tutorials
### Paid Videos ### Paid Videos
* [Standards and Best practices](http://teamtreehouse.com/library/standards-and-best-practices) * [Standards and Best practices](https://teamtreehouse.com/library/php-standards-and-best-practices)
* [PHP Training on Pluralsight](http://www.pluralsight.com/search/?searchTerm=php) * [PHP Training on Pluralsight](https://www.pluralsight.com/search?q=php)
* [PHP Training on Lynda.com](http://www.lynda.com/search?q=php) * [PHP Training on Lynda.com](https://www.lynda.com/search?q=php)
* [PHP Training on Tutsplus](http://code.tutsplus.com/categories/php/courses) * [PHP Training on Tutsplus](https://code.tutsplus.com/categories/php/courses)
* [Laracasts](https://laracasts.com/) * [Laracasts](https://laracasts.com/)

View File

@@ -31,7 +31,5 @@ security terms and provides some examples of them in every day PHP
* [Scaling PHP](http://www.scalingphpbook.com/) - Stop playing sysadmin and get back to coding * [Scaling PHP](http://www.scalingphpbook.com/) - 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 * [Signaling PHP](https://leanpub.com/signalingphp) - PCNLT signals are a great help when writing PHP scripts that
run from the command line. run from the command line.
* [The Grumpy Programmer's Guide To Building Testable PHP Applications](https://leanpub.com/grumpy-testing) - Learning
to write testable code doesn't have to suck.
* [Minimum Viable Tests](https://leanpub.com/minimumviabletests) - Long-time PHP testing evangelist Chris Hartjes goes over what he feels is the minimum you need to know to get started. * [Minimum Viable Tests](https://leanpub.com/minimumviabletests) - Long-time PHP testing evangelist Chris Hartjes goes over what he feels is the minimum you need to know to get started.
* [Domain-Driven Design in PHP](https://leanpub.com/ddd-in-php) - See real examples written in PHP showcasing Domain-Driven Design Architectural Styles (Hexagonal Architecture, CQRS or Event Sourcing), Tactical Design Patterns, and Bounded Context Integration. * [Domain-Driven Design in PHP](https://leanpub.com/ddd-in-php) - See real examples written in PHP showcasing Domain-Driven Design Architectural Styles (Hexagonal Architecture, CQRS or Event Sourcing), Tactical Design Patterns, and Bounded Context Integration.

View File

@@ -14,8 +14,8 @@ friends! Other community resources include the Google+ PHP [Programmer community
[Read the Official PHP Events Calendar][php-calendar] [Read the Official PHP Events Calendar][php-calendar]
[php-irc]: http://webchat.freenode.net/?channels=phpc [php-irc]: https://webchat.freenode.net/?channels=phpc
[phpc-twitter]: https://twitter.com/phpc [phpc-twitter]: https://twitter.com/phpc
[php-programmers-gplus]: https://plus.google.com/u/0/communities/104245651975268426012 [php-programmers-gplus]: https://plus.google.com/u/0/communities/104245651975268426012
[php-so]: http://stackoverflow.com/questions/tagged/php [php-so]: https://stackoverflow.com/questions/tagged/php
[php-calendar]: http://php.net/cal.php [php-calendar]: https://secure.php.net/cal.php

View File

@@ -6,9 +6,9 @@ anchor: user_groups
## PHP User Groups {#user_groups_title} ## PHP User Groups {#user_groups_title}
If you live in a larger city, odds are there's a PHP user group nearby. You can easily find your local PUG at If you live in a larger city, odds are there's a PHP user group nearby. You can easily find your local PUG at
the [usergroup-list at php.net][php-uglist] which is based upon [PHP.ug][php-ug]. Alternate sources might be [PHP.ug][php-ug]. Alternate sources might be [Meetup.com][meetup] or a search for ```php user group near me```
[Meetup.com][meetup] or a search for ```php user group near me``` using your favorite search engine using your favorite search engine (i.e. [Google][google]). If you live in a smaller town, there may not be a
(i.e. [Google][google]). If you live in a smaller town, there may not be a local PUG; if that's the case, start one! 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 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. online user group meetings with presentations by some of the top speakers in the PHP community.
@@ -20,8 +20,7 @@ generally promote the creating of a "female friendly" and professional atmospher
[google]: https://www.google.com/search?q=php+user+group+near+me [google]: https://www.google.com/search?q=php+user+group+near+me
[meetup]: http://www.meetup.com/find/ [meetup]: http://www.meetup.com/find/
[php-ug]: http://php.ug/ [php-ug]: https://php.ug/
[NomadPHP]: https://nomadphp.com/ [NomadPHP]: https://nomadphp.com/
[PHPWomen]: http://phpwomen.org/ [PHPWomen]: http://phpwomen.org/
[php-wiki]: https://wiki.php.net/usergroups [php-wiki]: https://wiki.php.net/usergroups
[php-uglist]: http://php.net/ug.php

View File

@@ -12,4 +12,4 @@ industry leaders.
[Find a PHP Conference][php-conf] [Find a PHP Conference][php-conf]
[php-conf]: http://php.net/conferences/index.php [php-conf]: https://secure.php.net/conferences/index.php

View File

@@ -10,6 +10,6 @@ anchor: elephpants
[Interview with Vincent Pontier][vincent-pontier-interview] [Interview with Vincent Pontier][vincent-pontier-interview]
[elephpant]: http://php.net/elephpant.php [elephpant]: https://secure.php.net/elephpant.php
[vincent-pontier-interview]: http://7php.com/elephpant/ [vincent-pontier-interview]: https://7php.com/elephpant/
[vincent-pontier]: http://www.elroubio.net/ [vincent-pontier]: http://www.elroubio.net/

View File

@@ -8,7 +8,7 @@ sitemap: true
PHP supports first-class functions, meaning that a function can be assigned to a variable. Both user-defined and PHP supports first-class functions, meaning that a function can be assigned to a variable. Both user-defined and
built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to
other functions and a function can return other functions (a feature called higher-order functions). other functions and a function can return other functions (a feature called higher-order functions).
Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code
focus is on iteration. focus is on iteration.
@@ -71,12 +71,12 @@ $output = array_filter($input, criteria_greater_than(3));
print_r($output); // items > 3 print_r($output); // items > 3
{% endhighlight %} {% endhighlight %}
Each filter function in the family accepts only elements greater than some minimum value. Single filter returned by Each filter function in the family accepts only elements greater than some minimum value. The 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 a closure with `$min` argument closed by the value in the scope (given as an argument when
`criteria_greater_than` is called). `criteria_greater_than` is called).
Early binding is used by default for importing `$min` variable into the created function. For true closures with late 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 a closure is
defined to capture variables in scope and access them later when the anonymous function is evaluated. defined to capture variables in scope and access them later when the anonymous function is evaluated.
* [Read about Anonymous functions][anonymous-functions] * [Read about Anonymous functions][anonymous-functions]

View File

@@ -290,6 +290,26 @@ EOD; // closing 'EOD' must be on it's own line, and to th
* [Heredoc syntax](http://php.net/language.types.string#language.types.string.syntax.heredoc) * [Heredoc syntax](http://php.net/language.types.string#language.types.string.syntax.heredoc)
> It should be noted that multiline strings can also be formed by continuing them across multilines in a statement. _e.g._
{% highlight php %}
$str = "
Example of string
spanning multiple lines
using statement syntax.
$a are parsed.
";
/**
* Output:
*
* Example of string
* spanning multiple lines
* using statement syntax.
* Variables are parsed.
*/
{% endhighlight %}
### Which is quicker? ### Which is quicker?
There is a myth floating around that single quote strings are fractionally quicker than double quote strings. This is There is a myth floating around that single quote strings are fractionally quicker than double quote strings. This is