CINXE.COM
PHP: The Right Way
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>PHP: The Right Way</title> <meta name="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 name="robots" content="index,follow,archive"/> <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:height" content="640"/> <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:url" content="https://www.phptherightway.com"/> <meta property="og:site_name" content="PHP: The Right Way"/> <meta property="og:type" content="website"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <link rel="icon" href="images/favicon.png" type="image/png"/> <link rel="stylesheet" href="styles/syntax.css"> <style> *{box-sizing:border-box}body{font-size:24px;line-height:32px;text-rendering:optimizeLegibility;word-wrap:break-word}h1,h2,h3,h4{font-family:georgia,serif}h1,.alpha{position:relative;font-size:48px;font-weight:normal;line-height:50px;text-align:center}h2,.beta{font-size:32px;font-weight:normal;line-height:36px}h3,.gamma{font-size:24px;font-weight:bold;line-height:30px}blockquote{border-left:3px solid #ccc;padding-left:20px;color:#777;font-style:italic;word-wrap:break-word}a{color:#4f5b93}a:hover{color:#8892bf}.back-to-top{text-align:center}.back-to-top a{background:#4f5b93;border-radius:3px;display:inline-block;height:40px;padding:0 20px;transition:all .1s ease;color:white;font-family:verdana,sans-serif;font-size:13px;line-height:40px;text-decoration:none;text-transform:uppercase}.back-to-top a:hover{background:#8892bf}img{max-width:100%}pre,code{color:#444;font-family:"Source Code Pro",Consolas,"Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;font-size:90%}a pre,a code{color:inherit}pre{background:#f7f7f7;border:1px solid #eee;border-radius:3px;display:block;overflow:auto;padding:20px;width:100%}@media (max-width:767px){body{font-size:18px;line-height:24px}h1,.alpha{font-size:36px;line-height:38px}h2,.beta{font-size:24px;line-height:28px}h3,.gamma{font-size:18px;line-height:23px}blockquote{margin-left:0}ul,ol{padding-left:1em}pre{padding:5px 10px}}@media (max-width:360px){body{font-size:16px;line-height:21px}h1,.alpha{font-size:28px;line-height:30px}h2,.beta{font-size:20px;line-height:23px}h3,.gamma{font-size:16px;line-height:20px}}.site-header{padding-top:40px;margin-bottom:40px;text-align:center}.site-header h1{margin:0;font-size:72px;line-height:60px}.site-header h1 em{display:block;font-size:34px;font-style:normal}.site-header h1 a{color:#333;text-decoration:none}.site-header h1 a:hover{color:#8892bf}.site-header .build-date{margin-bottom:10px;color:#999;font-family:verdana,sans-serif;font-size:11px;text-transform:uppercase}.site-header .btn-share{background:#8892bf;border-radius:3px;display:inline-block;height:30px;padding:0 20px;vertical-align:baseline;color:white;font-family:verdana,sans-serif;font-size:12px;line-height:30px;text-decoration:none;text-transform:uppercase}.site-header .fork-me{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJUAAACVCAMAAABmfEh9AAAAMFBMVEXr6+wSFiH////U1NT09PSRk5hucHb5+flMT1f8/Py+v8EtMDpXWWE8P0hgY2rg4OD5mIG8AAAFoElEQVR4AbSb0W4sKQxEyxfMdAyG///b1bCt3MSZ1CKth4coj0fVVp0GevDnc318POqj9cvlv1efl9taC6j18fj4+JO7AlWtrY9LDtblboVg5VKh9XkdpTUIVjIVsJqcPUSSVi7VowJ4pjWOHuKViUWodljlcOR9XN1KCVhpVOERPrHGOBz5gJVJFcN6Yp2NfHiIiVQxrI0l1xFWXlqE6vMZltOCGCGtbKqIdVgQI6SVRMXS6m9teUJFsI6dGNLKpgpYMg5Hvoe0cqhCPzz4yGemRagSRj6klUsV0zp2Ykgrg+r/j7zPK6SVSxXTmr/Lp2miEwMVTYs5cQKa5URCFdPiI9+AAg0FEdJKpootP14l1cTQ8p0YqXhaEcpEuvbvqg5ppVPF2RrfoSoKNMeJnIr31vDvM9XE4Ektz6m4E/3zaTn2PE1pLdmJnIo78aa5FuryKJ8R08qm4k70hTaXSsSKs5VNxZ24a6GsN+x8OBV34jIRhYpHJ8aWT6WKacXXwFKGYokv28l9gYstn00V0/IvWL4A8/1XxKD8aCSTird8G3vk1bpVFeFOzKTiTtxQEpLaKzoxmYqPfMG8oXps+ejEZKqANfu4PhF8Q1UsLOdOTKfiThSDVW3TU5zIqc5bXh+q6In7RE5F0vIvI9+bmEUi7sQ8KpJWh95TluFETnXuxG5+14RmOJFTnRdEv6FQWsZpIKc6d+INpYYZsKITk6m4E0W8YEqrZZ6nlURFnNgXpvhaBRqxRkgrnYqcnbYmvjAES4Q7MZkqphWceD3jumrIijgxj4qcQTTsuLy3IdyJqVQxrYjl9wYDsAMnplLFtOLID0AHDvaJyVSk5duUAisN7acTQ1r5VMSJAu2G1eUFVkgrnYq8NK/SxebBDVk+FXHiRPGzG7J8KuLEoXc07YpYwYnZVAc3ZApUPbghS6EiTgxQNhR+cEOWTMVuyC5Yl4kmMcL4dppPRZzY6i76rhi85fOpyA1Zg46FpoBFKYaWz6cip4EK1KbV2kKPaY2QVjYVaXlvXauJtHodODGXijhRGqyLFHSJKzoxn4rtqkVkHyHF5cGJyVQxrXhd0A2fTa+DOzFSJaYVjkZ03VAGANq5EyNVXlrhq5F2Q6HoMH5DFqmS0/IfTrRqz5isMCfmU3EnNvyLMyd1Yj4Vc6Ksv5WlSpyYT8X2ibC//xbixHwq4kSpRaQXF3Fpkzoxn4o4cZkCTSZUuBPzqUjL68KGWq6m3In5VMSJNqVhecMWkDpxYjYV2fn4TkqswrooCndipMpMa351omN5N+hU0ScfcWI6FTmxmS62rXhDOXFiOhVp+WvZhsK+ZVn+qxPzqchm31FcFGvtAVv+uxPzqUha0/bj87UsjFb4aiSfijqx7Ygc4Ddk+VTciebPP4CJk31iPhV34iara+5p/7Xl86m4E3dSu7mM/LogUr3fid3Wbq4u+55T24u03kZFnOjSlu3jNxGF/fx1wduo+FcjBbK9+ITq8tOJ76LiX1Jabe2GelUQ76QiTuyGuqFg80VBvJeKONE21KsTm+G9vJWKOFE21OeJTTgaeTMVSasBl0jI6nYip8qfrW9O1AY0+bneTMW/GrEKqLxYPZ+KpBWPRmb7p307SEEoBoIoqBAlIOj9byt/9rUT3yaeoGhhGkmL/2VY9ZdOvBcqdGKtQifWKnRircILWa3CaiRX+cr3KndiqvIvn1TlJWWqcidaVV/5QIUl5baqTytXuROtKjqxVqETaxU6sVahE1uVNzaxCp0Yqny33jtVeUmZqnzlU5WvfKpyWqnKaaUqr0ZSlVcjqcqrkVqFTsxVeCFrVE7rM51oVZTWsLZVRVrjur5Eq4K0xnXtcaEKWbf1fEFVsca1HlBFrHEtvKWGrIFBlbHGheVA6ZoPVK2rV/18dX9UR3VUR3VUX8Uz94M6xyeLAAAAAElFTkSuQmCC);background-position:top right;background-repeat:no-repeat;background-size:contain;height:100px;width:100px;position:absolute;top:0;right:0;z-index:100;width:120px}.site-navigation,.site-content,.site-footer{margin:0 auto;max-width:840px;width:92%}.site-navigation{-webkit-columns:3;-moz-columns:3;columns:3;-webkit-column-gap:40px;-moz-column-gap:40px;column-gap:40px}.site-navigation input[type="checkbox"],.site-navigation label{display:none}.site-navigation ul{list-style:none;margin:0;padding:0}.site-navigation ul li{margin-bottom:20px;font-size:22px;line-height:23px}.site-navigation ul li a{display:block;color:#444;font-weight:700;text-decoration:none}.site-navigation ul li a:hover{color:#8892bf}.site-navigation ul li ul{padding-top:8px}.site-navigation ul li li{margin-bottom:6px;font-size:18px}.site-navigation ul li li a{border:none;color:#777;font-weight:normal}.site-navigation li{-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}@media (max-width:820px){.site-navigation{-webkit-columns:2;-moz-columns:2;columns:2}}@media (max-width:560px){.site-navigation{-webkit-columns:1;-moz-columns:1;columns:1}}@media (max-width:375px){.site-navigation{background:rgba(255,255,255,0.95);-webkit-columns:1;-moz-columns:1;columns:1;max-height:100vh;position:fixed;bottom:0;left:0;z-index:100}.site-navigation label{background:#4f5b93;box-sizing:border-box;display:block;height:40px;padding:0 10px;width:100vh;position:absolute;bottom:0;left:0;color:white;font-family:verdana,sans-serif;font-size:13px;line-height:40px;text-transform:uppercase;z-index:2}.site-navigation>ul{background:rgba(255,255,255,0.96);border-top:3px solid #8892bf;box-shadow:rgba(0,0,0,0.25) 0 -5px 10px;box-sizing:border-box;padding:20px;overflow:auto;-webkit-overflow-scrolling:touch;position:absolute;left:0;bottom:40px;height:50vh;width:100vh;-webkit-transform:translate(0, 100vh);-ms-transform:translate(0, 100vh);transform:translate(0, 100vh);transition:all .2s ease;z-index:1}.site-navigation input[type="checkbox"]:checked~ul{-webkit-transform:translate(0, 0);-ms-transform:translate(0, 0);transform:translate(0, 0)}}.site-content h1{padding-top:40px;position:relative}.site-content h1:after{border:1px solid #ddd;border-bottom:none;content:"";display:block;height:8px;position:absolute;left:0;top:0;width:100%}.site-content.chapters{counter-reset:chapter}.site-content.chapters h1{counter-increment:chapter;padding-top:60px}.site-content.chapters h1:before{display:inline-block;content:"Chapter " counter(chapter) ".";position:absolute;top:30px;left:50%;-webkit-transform:translateX(-50%);-ms-transform:translateX(-50%);transform:translateX(-50%);color:#999;font-size:12px;letter-spacing:1px;line-height:20px;text-transform:uppercase;text-align:center}.site-content #welcome ul{-webkit-columns:3;-moz-columns:3;columns:3;-webkit-column-gap:30px;-moz-column-gap:30px;column-gap:30px;list-style-position:inside}.site-content .back-to-top{margin-bottom:60px}@media (max-width:870px){.site-content #welcome ul{-webkit-columns:2;-moz-columns:2;columns:2}}@media (max-width:600px){.site-content #welcome ul{-webkit-columns:1;-moz-columns:1;columns:1}}.site-footer{border-top:1px solid #ccc;margin:60px auto 0 auto;padding:40px 20px;font-family:verdana,sans-serif;font-size:16px;text-align:center}.site-footer .cc-badge{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFgAAAAfCAMAAABUFvrSAAAAw1BMVEX///8AAAAAAACrsar///8oKSjR1NAODg4jHyDLz8pAPz/f399wcHBQUFBgYGDJzcjEyMN5fHkwMDC9wry4vbeAgIDw8PDBxcDO0c3M0MyUmJPGysW6v7q/v7+fn5/T1tKvtK61urSxt7C/w76zuLKhpKDk5OSRk5F2c3RQUVAbGxuts6yEhoR9fnxDREMgICDW1dXJyMirq6qvr68wLS3Pz8+Rj4+Pj4+LioqEgYJaV1i6ubmbl5meoJ1dXl06NjcZGRmWw6QEAAAAAnRSTlMMANomgjQAAAMCSURBVHjatZYJc6JAEIWznWFmOAQDguAdjUqMd0yi5vz/v2q7GTmkNusWW3kxNfJkPts3TMPVFfyIfiH3ttHwRs1623F0PYp03XHa9ebI6zRu74aDwcPDdQUBXCG3440Qq4ec91GchzqhM/J1FSEYuVguYudLASixnBM6JVPJNxqgtJts2mWHwMh1Ij6dQabZlEeKfDccDlo4xbAsA6e11KzLDoG9EXHvqVbb73Z9m+q+r4dEppLHAmomQ5k1EMmsi44CY74JV/gBU+ohWqtjzSMMY6iBjR4AfQAaTVLO87HkTDabiXIUuNnWieuaLFPgYs1cb1PJC6itUzCrwQ2mCe4bcr9EPEkdOmcsUa+Jo8B1J5wiF8s9J0/DpGQNCt9ogkbladKwwZ/DNnNMtpGfdizlMzkKjAXPQDyxMwUCZqpkMOjYBrBpNADnGDESZDxZ5w4L3uQec5A7chTYCecAPiupBzDHkr0OWHQIKBotwqCzidGI17kTSKlhzFJOyFFgvgSBQXRrhuGr4QUnCFhyzOIbMDLinZTH18y523UTsJmBdS7ARiCQjEcg2fTjBdfrzc6foqCsemwtUUbqvI43jG2lxHMyMACW6MLK7K56Lrjm46qXZNGnkE+LB5AvHjlHudtBvF3MUqcn5eGgybd88aI+AP4KlbMaSF0ERwj2ocZKlxs5k8OXeA6KzkGirICcfwI3ChvEKm6Q/bHkbLbbtXLKUQRPKx+joCGPorGttKXzxTutWrZ41mnxGrdjDcC1LTdvOZcddbndg2DZ5fZoJANbqcuNGtygWttMdvTLtxsE+1uFXp9vafO7LV0ZTE3o/S9NqBqXwLDQ+QeSC23IVG1zDtVFYLD0s0Yf+ALgk0cL+F8wLCL+Ubo18agFqdT+oDeZo/7RL53EzsGUxnvpZtoqzDm9WO6o49JXKaMIpjRCPk1v/1Me6sUc0rZZcE5/BaXtpAQGd4Bozul5BbEDAwoqB6GcrOLcLFesZOw99Yjl7Ql7oeIUXjynBP4h/djT5m+nuF33PcPucwAAAABJRU5ErkJggg==);background-position:top left;background-repeat:no-repeat;background-size:contain;display:inline-block;height:31px;width:88px}.site-footer h2{font-size:24px;font-weight:bold;line-height:30px;margin-bottom:10px}.site-footer ul{list-style:none;margin:0 0 20px 0;padding:0}.site-footer .license{color:#777;font-size:13px} </style> </head> <body> <header class="site-header"> <h1><a href="/">PHP <em>The Right Way</em></a></h1> <div class="build-date">Last Updated: 2024-09-30 09:53:13 +0000</div> <div class="share"> <a class="btn-share" href="https://twitter.com/intent/tweet?text=PHP+The+Right+Way&url=https%3A%2F%2Fwww.phptherightway.com&hashtags=PHP" target="_blank">Share on Twitter</a> </div> <a class="fork-me" href="https://github.com/codeguy/php-the-right-way" target="_blank"></a> </header> <nav class="site-navigation"> <input type="checkbox" id="toggle"/> <label for="toggle">Table of Contents</label> <ul> <li><a href="/#welcome">Welcome</a> <ul> <li><a href="/#translations">Translations</a></li> <li><a href="/#how-to-contribute">How to Contribute</a></li> </ul> </li> <li><a href="/#getting_started">Getting Started</a> <ul> <li><a href="/#use_the_current_stable_version">Use the Current Stable Version (8.3)</a> </li> <li><a href="/#builtin_web_server">Built-in Web Server</a> </li> <li><a href="/#mac_setup">Mac Setup</a> </li> <li><a href="/#windows_setup">Windows Setup</a> </li> <li><a href="/#linux_setup">Linux Setup</a> </li> <li><a href="/#common_directory_structure">Common Directory Structure</a> </li> </ul> </li> <li><a href="/#code_style_guide">Code Style Guide</a> <ul> </ul> </li> <li><a href="/#language_highlights">Language Highlights</a> <ul> <li><a href="/#programming_paradigms">Programming Paradigms</a> </li> <li><a href="/#namespaces">Namespaces</a> </li> <li><a href="/#standard_php_library">Standard PHP Library</a> </li> <li><a href="/#command_line_interface">Command Line Interface</a> </li> <li><a href="/#xdebug">Xdebug</a> </li> </ul> </li> <li><a href="/#dependency_management">Dependency Management</a> <ul> <li><a href="/#composer_and_packagist">Composer and Packagist</a> </li> <li><a href="/#pear">PEAR</a> </li> </ul> </li> <li><a href="/#coding_practices">Coding Practices</a> <ul> <li><a href="/#the_basics">The Basics</a> </li> <li><a href="/#date_and_time">Date and Time</a> </li> <li><a href="/#design_patterns">Design Patterns</a> </li> <li><a href="/#php_and_utf8">Working with UTF-8</a> </li> <li><a href="/#i18n_l10n">Internationalization and Localization</a> </li> </ul> </li> <li><a href="/#dependency_injection">Dependency Injection</a> <ul> <li><a href="/#basic_concept">Basic Concept</a> </li> <li><a href="/#complex_problem">Complex Problem</a> </li> <li><a href="/#containers">Containers</a> </li> <li><a href="/#further_reading">Further Reading</a> </li> </ul> </li> <li><a href="/#databases">Databases</a> <ul> <li><a href="/#mysql_extension">MySQL Extension</a> </li> <li><a href="/#pdo_extension">PDO Extension</a> </li> <li><a href="/#databases_interacting">Interacting with Databases</a> </li> <li><a href="/#databases_abstraction_layers">Abstraction Layers</a> </li> </ul> </li> <li><a href="/#templating">Templating</a> <ul> <li><a href="/#templating_benefits">Benefits</a> </li> <li><a href="/#plain_php_templates">Plain PHP Templates</a> </li> <li><a href="/#compiled_templates">Compiled Templates</a> </li> <li><a href="/#templating_further_reading">Further Reading</a> </li> </ul> </li> <li><a href="/#errors_and_exceptions">Errors and Exceptions</a> <ul> <li><a href="/#errors">Errors</a> </li> <li><a href="/#exceptions">Exceptions</a> </li> </ul> </li> <li><a href="/#security">Security</a> <ul> <li><a href="/#web_application_security">Web Application Security</a> </li> <li><a href="/#password_hashing">Password Hashing</a> </li> <li><a href="/#data_filtering">Data Filtering</a> </li> <li><a href="/#configuration_files">Configuration Files</a> </li> <li><a href="/#register_globals">Register Globals</a> </li> <li><a href="/#error_reporting">Error Reporting</a> </li> </ul> </li> <li><a href="/#testing">Testing</a> <ul> <li><a href="/#test_driven_development">Test Driven Development</a> </li> <li><a href="/#behavior_driven_development">Behavior Driven Development</a> </li> <li><a href="/#complementary_testing_tools">Complementary Testing Tools</a> </li> </ul> </li> <li><a href="/#servers_and_deployment">Servers and Deployment</a> <ul> <li><a href="/#platform_as_a_service">Platform as a Service (PaaS)</a> </li> <li><a href="/#virtual_or_dedicated_servers">Virtual or Dedicated Servers</a> </li> <li><a href="/#shared_servers">Shared Servers</a> </li> <li><a href="/#building_and_deploying_your_application">Building Your Application</a> </li> </ul> </li> <li><a href="/#virtualization">Virtualization</a> <ul> <li><a href="/#vagrant">Vagrant</a> </li> <li><a href="/#docker">Docker</a> </li> </ul> </li> <li><a href="/#caching">Caching</a> <ul> <li><a href="/#opcode_cache">Opcode Cache</a> </li> <li><a href="/#object_caching">Object Caching</a> </li> </ul> </li> <li><a href="/#documenting">Documenting your Code</a> <ul> <li><a href="/#phpdoc">PHPDoc</a> </li> </ul> </li> <li><a href="/#resources">Resources</a> <ul> <li><a href="/#from_the_source">From the Source</a> </li> <li><a href="/#people_to_follow">People to Follow</a> </li> <li><a href="/#php_paas_providers">PHP PaaS Providers</a> </li> <li><a href="/#frameworks">Frameworks</a> </li> <li><a href="/#components">Components</a> </li> <li><a href="/#other_resources">Other Useful Resources</a> </li> <li><a href="/#videos">Video Tutorials</a> </li> <li><a href="/#books">Books</a> </li> </ul> </li> <li><a href="/#community">Community</a> <ul> <li><a href="/#user_groups">User Groups</a> </li> <li><a href="/#conferences">Conferences</a> </li> <li><a href="/#elephpants">Elephpants</a> </li> </ul> </li> <li><a href="/#credits">Credits</a></li> </ul> </nav> <div class="site-content chapters"> <section class="chapter" id="welcome"> <h1 id="welcome">Welcome</h1> <p>There’s a lot of outdated information on the Web that leads new PHP users astray, propagating bad practices and insecure code. <em>PHP: The Right Way</em> is an easy-to-read, quick reference for PHP popular coding standards, links to authoritative tutorials around the Web, and what the contributors consider to be best practices at present.</p> <p><em>There is no canonical way to use PHP</em>. This website aims to introduce new PHP developers to some topics which they may not discover until it is too late, and aims to give seasoned pros some fresh ideas on those topics they’ve been doing for years without ever reconsidering. This website will also not tell you which tools to use, but instead offer suggestions for multiple options, when possible explaining the differences in approach and use-case.</p> <p>This is a living document and will continue to be updated with more helpful information and examples as they become available.</p> <h2 id="translations">Translations</h2> <p><em>PHP: The Right Way</em> is translated into many different languages:</p> <ul> <li><a href="https://www.phptherightway.com">English</a></li> <li><a href="https://phpdevenezuela.github.io/php-the-right-way">Español</a></li> <li><a href="https://eilgin.github.io/php-the-right-way/">Français</a></li> <li><a href="https://id.phptherightway.com">Indonesia</a></li> <li><a href="https://it.phptherightway.com">Italiano</a></li> <li><a href="https://pl.phptherightway.com">Polski</a></li> <li><a href="https://br.phptherightway.com">Português do Brasil</a></li> <li><a href="https://bgui.github.io/php-the-right-way/">Română</a></li> <li><a href="https://sl.phptherightway.com">Slovenščina</a></li> <li><a href="https://phpsrbija.github.io/php-the-right-way/">Srpski</a></li> <li><a href="https://hkulekci.github.io/php-the-right-way/">Türkçe</a></li> <li><a href="https://bg.phptherightway.com">български</a></li> <li><a href="https://getjump.github.io/ru-php-the-right-way">Русский язык</a></li> <li><a href="https://iflista.github.io/php-the-right-way/">Українська</a></li> <li><a href="https://adaroobi.github.io/php-the-right-way/">العربية</a></li> <li><a href="https://novid.github.io/php-the-right-way/">فارسى</a></li> <li><a href="https://apzentral.github.io/php-the-right-way/">ภาษาไทย</a></li> <li><a href="https://modernpug.github.io/php-the-right-way">한국어판</a></li> <li><a href="https://ja.phptherightway.com">日本語</a></li> <li><a href="https://laravel-china.github.io/php-the-right-way/">简体中文</a></li> <li><a href="https://laravel-taiwan.github.io/php-the-right-way">繁體中文</a></li> </ul> <h2 id="book">Book</h2> <p>The most recent version of <em>PHP: The Right Way</em> is also available in PDF, EPUB and MOBI formats. <a href="https://leanpub.com/phptherightway">Go to Leanpub</a></p> <h2 id="how-to-contribute">How to Contribute</h2> <p>Help make this website the best resource for new PHP programmers! <a href="https://github.com/codeguy/php-the-right-way/tree/gh-pages">Contribute on GitHub</a></p> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="getting_started"> <h1 id="getting_started_title">Getting Started</h1> </section> <section class="chapter" id="use_the_current_stable_version"> <h2 id="use_the_current_stable_version_title">Use the Current Stable Version (8.3)</h2> <p>If you are getting started with PHP, start with the current stable release of <a href="https://www.php.net/downloads.php">PHP 8.3</a>. PHP 8.x adds many <a href="#language_highlights">new features</a> over the older 7.x and 5.x versions. The engine has been largely re-written, and PHP is now even quicker than older versions. PHP 8 is a major update of the language and contains many new features and optimizations.</p> <p>You should try to upgrade to the latest stable version quickly - PHP 7.4 <a href="https://www.php.net/supported-versions.php">is already End of Life</a>. Upgrading is easy, as there are not many backwards compatibility breaks <a href="https://www.php.net/manual/migration80.incompatible.php">PHP 8.0</a>, <a href="https://www.php.net/manual/migration81.incompatible.php">PHP 8.1</a>, <a href="https://www.php.net/manual/migration82.incompatible.php">PHP 8.2</a>, <a href="https://www.php.net/manual/migration83.incompatible.php">PHP 8.3</a>. If you are not sure which version a function or feature is in, you can check the PHP documentation on the <a href="https://www.php.net/manual/">php.net</a> website.</p> </section> <section class="chapter" id="builtin_web_server"> <h2 id="builtin_web_server_title">Built-in web server</h2> <p>With PHP 5.4 or newer, you can start learning PHP without installing and configuring a full-fledged web server. To start the server, run the following command from your terminal in your project’s web root:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="gp">></span><span class="w"> </span>php <span class="nt">-S</span> localhost:8000</code></pre></figure> <ul> <li><a href="https://www.php.net/features.commandline.webserver">Learn about the built-in, command line web server</a></li> </ul> </section> <section class="chapter" id="mac_setup"> <h2 id="mac_setup_title">macOS Setup</h2> <p>macOS 12 (Monterey) and later does not come prepackaged with PHP. Earlier macOS versions include PHP but are behind the latest stable release. There are multiple ways to install the latest PHP version on macOS.</p> <h3 id="install-php-via-homebrew">Install PHP via Homebrew</h3> <p><a href="https://brew.sh/">Homebrew</a> is a package manager for macOS that helps you easily install PHP and various extensions. The Homebrew core repository provides “formulae” for PHP 7.4, 8.0, 8.1, 8.2 and PHP 8.3. Install the latest version with this command:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>brew install php@8.3 </code></pre></div></div> <p>You can switch between Homebrew PHP versions by modifying your <code class="language-plaintext highlighter-rouge">PATH</code> variable. Alternatively, you can use <a href="https://github.com/philcook/brew-php-switcher">brew-php-switcher</a> to switch PHP versions automatically.</p> <p>You can also switch between PHP versions manually by unlinking and linking the wanted version:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>brew unlink php brew link --overwrite php@8.2 </code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>brew unlink php brew link --overwrite php@8.3 </code></pre></div></div> <h3 id="install-php-via-macports">Install PHP via Macports</h3> <p>The <a href="https://www.macports.org/install.php">MacPorts</a> Project is an open-source community initiative to design an easy-to-use system for compiling, installing, and upgrading either command-line, X11 or Aqua based open-source software on the macOS operating system.</p> <p>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 have any package installed on your system.</p> <p>At this point, you can install <code class="language-plaintext highlighter-rouge">php54</code>, <code class="language-plaintext highlighter-rouge">php55</code>, <code class="language-plaintext highlighter-rouge">php56</code>, <code class="language-plaintext highlighter-rouge">php70</code>, <code class="language-plaintext highlighter-rouge">php71</code>, <code class="language-plaintext highlighter-rouge">php72</code>, <code class="language-plaintext highlighter-rouge">php73</code>, <code class="language-plaintext highlighter-rouge">php74</code>, <code class="language-plaintext highlighter-rouge">php80</code>, <code class="language-plaintext highlighter-rouge">php81</code>, <code class="language-plaintext highlighter-rouge">php82</code> or <code class="language-plaintext highlighter-rouge">php83</code> using the <code class="language-plaintext highlighter-rouge">port install</code> command, for example:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sudo port install php74 sudo port install php83 </code></pre></div></div> <p>And you can run <code class="language-plaintext highlighter-rouge">select</code> command to switch your active PHP:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sudo port select --set php php83 </code></pre></div></div> <h3 id="install-php-via-phpbrew">Install PHP via phpbrew</h3> <p><a href="https://github.com/phpbrew/phpbrew">phpbrew</a> is a tool for installing and managing multiple PHP versions. This can be really useful if two different applications/projects require different versions of PHP, and you are not using virtual machines.</p> <h3 id="install-php-via-liips-binary-installer">Install PHP via Liip’s binary installer</h3> <p>Another popular option is <a href="https://web.archive.org/web/20220505163210/https://php-osx.liip.ch/">php-osx.liip.ch</a> which provides one liner installation methods for versions 5.3 through 7.3. It doesn’t overwrite the PHP binaries installed by Apple, but installs everything in a separate location (/usr/local/php5).</p> <h3 id="compile-from-source">Compile from Source</h3> <p>Another option that gives you control over the version of PHP you install, is to <a href="https://www.php.net/install.macosx.compile">compile it yourself</a>. In that case be sure to have installed either <a href="https://github.com/kennethreitz/osx-gcc-installer">Xcode</a> or Apple’s substitute <a href="https://developer.apple.com/downloads">“Command Line Tools for XCode”</a> downloadable from Apple’s Developer Center.</p> <h3 id="all-in-one-installers">All-in-One Installers</h3> <p>The solutions listed above mainly handle PHP itself, and do not supply things like <a href="https://httpd.apache.org/">Apache</a>, <a href="https://www.nginx.com/">Nginx</a> or a SQL server. “All-in-one” solutions such as <a href="https://www.mamp.info/en/downloads/">MAMP</a> and <a href="https://www.apachefriends.org/">XAMPP</a> 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.</p> </section> <section class="chapter" id="windows_setup"> <h2 id="windows_setup_title">Windows Setup</h2> <p>You can download the binaries from <a href="https://windows.php.net/download/">windows.php.net/download</a>. After the extraction of PHP, it is recommended to set the <a href="https://www.windows-commandline.com/set-path-command-line/">PATH</a> to the root of your PHP folder (where php.exe is located) so you can execute PHP from anywhere.</p> <p>For learning and local development, you can use the built in webserver with PHP 5.4+ so you don’t need to worry about configuring it. If you would like an “all-in-one” which includes a full-blown webserver and MySQL too then tools such as the <a href="https://www.apachefriends.org/">XAMPP</a>, <a href="https://www.easyphp.org/">EasyPHP</a>, <a href="https://ospanel.io/">OpenServer</a> and <a href="https://www.wampserver.com/en/">WAMP</a> will help get a Windows development environment up and running fast. That said, these tools will be a little different from production so be careful of environment differences if you are working on Windows and deploying to Linux.</p> <p>If you need to run your production system on Windows, then IIS7 will give you the most stable and best performance. You can use <a href="http://phpmanager.codeplex.com/">phpmanager</a> (a GUI plugin for IIS7) to make configuring and managing PHP simple. IIS7 comes with FastCGI built in and ready to go, you just need to configure PHP as a handler. For support and additional resources there is a <a href="https://php.iis.net/">dedicated area on iis.net</a> for PHP.</p> <p>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 <a href="/#virtualization_title">Virtual Machine</a>.</p> <p>Chris Tankersley has a very helpful blog post on what tools he uses to do <a href="https://ctankersley.com/2016/11/13/developing-on-windows-2016/">PHP development using Windows</a>.</p> </section> <section class="chapter" id="linux_setup"> <h2 id="linux_setup_title">Linux Setup</h2> <p>Most GNU/Linux distributions come with PHP available from the official repositories, but those packages usually are a little behind the current stable version. There are multiple ways to get newer PHP versions on such distributions. On Ubuntu and Debian-based GNU/Linux distributions, for instance, the best alternatives for native packages are provided and maintened by <a href="https://deb.sury.org/">Ondřej Surý</a>, through his Personal Package Archive (PPA) on Ubuntu and DPA/bikeshed on Debian. Find instructions for each of these below. All that said, you can always use containers, compile the PHP Source code, etc.</p> <h3 id="ubuntu-based-distributions">Ubuntu-based distributions</h3> <p>For Ubuntu distributions, the <a href="https://launchpad.net/~ondrej/+archive/ubuntu/php">PPA by Ondřej Surý</a> provides supported PHP versions along with many PECL extensions. To add this PPA to your system, perform the following steps in your terminal:</p> <ol> <li> <p>First, add the PPA to your system’s software sources using the command:</p> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>add-apt-repository ppa:ondrej/php </code></pre></div> </div> </li> <li> <p>After adding the PPA, update your system’s package list:</p> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>apt update </code></pre></div> </div> </li> </ol> <p>This will ensure that your system can access and install the latest PHP packages available in the PPA.</p> <h4 id="debian-based-distributions">Debian-based distributions</h4> <p>For Debian-based distributions, Ondřej Surý also provides a <a href="https://packages.sury.org/php/">bikeshed</a> (Debian equivalent of a PPA). To add the bikeshed to your system and update it, follow these steps:</p> <ol> <li> <p>Ensure that you have root access. If not, you might need to use <code class="language-plaintext highlighter-rouge">sudo</code> for the following commands.</p> </li> <li> <p>Update your system’s package list:</p> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>apt-get update </code></pre></div> </div> </li> <li> <p>Install <code class="language-plaintext highlighter-rouge">lsb-release</code>, <code class="language-plaintext highlighter-rouge">ca-certificates</code>, and <code class="language-plaintext highlighter-rouge">curl</code>:</p> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>apt-get <span class="nt">-y</span> <span class="nb">install </span>lsb-release ca-certificates curl </code></pre></div> </div> </li> <li> <p>Download the signing key for the repository:</p> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>curl <span class="nt">-sSLo</span> /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg </code></pre></div> </div> </li> <li> <p>Add the repository to your system’s software sources:</p> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>sh <span class="nt">-c</span> <span class="s1">'echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'</span> </code></pre></div> </div> </li> <li> <p>Finally, update your system’s package list again:</p> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>apt-get update </code></pre></div> </div> </li> </ol> <p>With these steps, your system will be able to install the latest PHP packages from the bikeshed.</p> </section> <section class="chapter" id="common_directory_structure"> <h2 id="common_directory_structure_title">Common Directory structure</h2> <p>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 <code class="language-plaintext highlighter-rouge">DocumentRoot</code> is.” Although this answer is not complete, it’s a great place to start.</p> <p>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.</p> <p>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.</p> <p><a href="https://paul-m-jones.com/">Paul M. Jones</a> 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 <a href="https://github.com/php-pds/skeleton">Standard PHP Package Skeleton</a>, based on this research. In this directory structure, <code class="language-plaintext highlighter-rouge">DocumentRoot</code> should point to <code class="language-plaintext highlighter-rouge">public/</code>, unit tests should be in the <code class="language-plaintext highlighter-rouge">tests/</code> directory, and third party libraries, as installed by <a href="/#composer_and_packagist">composer</a>, belong in the <code class="language-plaintext highlighter-rouge">vendor/</code> directory. For other files and directories, abiding by the <a href="https://github.com/php-pds/skeleton">Standard PHP Package Skeleton</a> will make the most sense to contributors of a project.</p> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="code_style_guide"> <h1 id="code_style_guide_title">Code Style Guide</h1> <p>The PHP community is large and diverse, composed of innumerable libraries, frameworks, and components. It is common for PHP developers to choose several of these and combine them into a single project. It is important that PHP code adheres (as close as possible) to a common code style to make it easy for developers to mix and match various libraries for their projects.</p> <p>The <a href="https://www.php-fig.org/">Framework Interop Group</a> has proposed and approved a series of style recommendations. Not all of them relate to code-style, but those that do are <a href="https://www.php-fig.org/psr/psr-1/">PSR-1</a>, <a href="https://www.php-fig.org/psr/psr-12/">PSR-12</a>, <a href="https://www.php-fig.org/psr/psr-4/">PSR-4</a> and <a href="https://www.php-fig.org/per/coding-style/">PER Coding Style</a>. These 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 personal style.</p> <p>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 applications that implement the components can have consistency even when working with lots of third-party code.</p> <ul> <li><a href="https://www.php-fig.org/psr/psr-1/">Read about PSR-1</a></li> <li><a href="https://www.php-fig.org/psr/psr-12/">Read about PSR-12</a></li> <li><a href="https://www.php-fig.org/psr/psr-4/">Read about PSR-4</a></li> <li><a href="https://www.php-fig.org/per/coding-style/">Read about PER Coding Style</a></li> <li><a href="https://pear.php.net/manual/en/standards.php">Read about PEAR Coding Standards</a></li> <li><a href="https://symfony.com/doc/current/contributing/code/standards.html">Read about Symfony Coding Standards</a></li> </ul> <p>You can use <a href="https://github.com/PHPCSStandards/PHP_CodeSniffer">PHP_CodeSniffer</a> to check code against any one of these recommendations, and plugins for text editors like <a href="https://github.com/benmatselby/sublime-phpcs">Sublime Text</a> to be given real-time feedback.</p> <p>You can fix the code layout automatically by using one of the following tools:</p> <ul> <li>One is the <a href="https://cs.symfony.com/">PHP Coding Standards Fixer</a> which has a very well tested codebase.</li> <li>Also, the <a href="https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki/Fixing-Errors-Automatically">PHP Code Beautifier and Fixer</a> tool which is included with PHP_CodeSniffer can be used to adjust your code accordingly.</li> </ul> <p>And you can run phpcs manually from shell:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>phpcs -sw --standard=PSR1 file.php </code></pre></div></div> <p>It will show errors and describe how to fix them. It can also be helpful to include the <code class="language-plaintext highlighter-rouge">phpcs</code> command in a git pre-commit hook with the <code class="language-plaintext highlighter-rouge">--filter=GitStaged</code> CLI argument. That way, code which contain violations against the chosen standard cannot enter the repository until those violations have been fixed.</p> <p>If you have PHP_CodeSniffer, then you can fix the code layout problems reported by it, automatically, with the <a href="https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki/Fixing-Errors-Automatically">PHP Code Beautifier and Fixer</a>.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>phpcbf -w --standard=PSR1 file.php </code></pre></div></div> <p>Another option is to use the <a href="https://cs.symfony.com/">PHP Coding Standards Fixer</a>. It will show what kind of errors the code structure had before it fixed them.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>php-cs-fixer fix -v --rules=@PSR1 file.php </code></pre></div></div> <p>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.</p> <p>Finally, a good supplementary resource for writing clean PHP code is <a href="https://github.com/jupeter/clean-code-php">Clean Code PHP</a>.</p> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="language_highlights"> <h1 id="language_highlights_title">Language Highlights</h1> </section> <section class="chapter" id="programming_paradigms"> <h2 id="programming_paradigms_title">Programming Paradigms</h2> <p>PHP is a flexible, dynamic language that supports a variety of programming techniques. It has evolved dramatically over the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in PHP 5.3 (2009), and traits in PHP 5.4 (2012).</p> <h3 id="object-oriented-programming">Object-oriented Programming</h3> <p>PHP has a very complete set of object-oriented programming features including support for classes, abstract classes, interfaces, inheritance, constructors, cloning, exceptions, and more.</p> <ul> <li><a href="https://www.php.net/language.oop5">Read about Object-oriented PHP</a></li> <li><a href="https://www.php.net/language.oop5.traits">Read about Traits</a></li> </ul> <h3 id="functional-programming">Functional Programming</h3> <p>PHP supports first-class functions, meaning that a function can be assigned to a variable. Both user-defined and built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to other functions (a feature called <em>Higher-order Functions</em>) and functions can return other functions.</p> <p>Recursion, a feature that allows a function to call itself, is supported by the language, but most PHP code is focused on iteration.</p> <p>New anonymous functions (with support for closures) are present since PHP 5.3 (2009).</p> <p>PHP 5.4 added the ability to bind closures to an object’s scope and also improved support for callables such that they can be used interchangeably with anonymous functions in almost all cases.</p> <ul> <li>Continue reading on <a href="/pages/Functional-Programming.html">Functional Programming in PHP</a></li> <li><a href="https://www.php.net/functions.anonymous">Read about Anonymous Functions</a></li> <li><a href="https://www.php.net/class.closure">Read about the Closure class</a></li> <li><a href="https://wiki.php.net/rfc/closures">More details in the Closures RFC</a></li> <li><a href="https://www.php.net/language.types.callable">Read about Callables</a></li> <li><a href="https://www.php.net/function.call-user-func-array">Read about dynamically invoking functions with <code class="language-plaintext highlighter-rouge">call_user_func_array()</code></a></li> </ul> <h3 id="meta-programming">Meta Programming</h3> <p>PHP supports various forms of meta-programming through mechanisms like the Reflection API and Magic Methods. There are many Magic Methods available like <code class="language-plaintext highlighter-rouge">__get()</code>, <code class="language-plaintext highlighter-rouge">__set()</code>, <code class="language-plaintext highlighter-rouge">__clone()</code>, <code class="language-plaintext highlighter-rouge">__toString()</code>, <code class="language-plaintext highlighter-rouge">__invoke()</code>, etc. that allow developers to hook into class behavior. Ruby developers often say that PHP is lacking <code class="language-plaintext highlighter-rouge">method_missing</code>, but it is available as <code class="language-plaintext highlighter-rouge">__call()</code> and <code class="language-plaintext highlighter-rouge">__callStatic()</code>.</p> <ul> <li><a href="https://www.php.net/language.oop5.magic">Read about Magic Methods</a></li> <li><a href="https://www.php.net/intro.reflection">Read about Reflection</a></li> <li><a href="https://www.php.net/language.oop5.overloading">Read about Overloading</a></li> </ul> </section> <section class="chapter" id="namespaces"> <h2 id="namespaces_title">Namespaces</h2> <p>As mentioned above, the PHP community has a lot of developers creating lots of code. This means that one library’s PHP code might use the same class name as another. When both libraries are used in the same namespace, they collide and cause trouble.</p> <p><em>Namespaces</em> solve this problem. As described in the PHP reference manual, namespaces may be compared to operating system directories that <em>namespace</em> files; two files with the same name may co-exist in separate directories. Likewise, two PHP classes with the same name may co-exist in separate PHP namespaces. It’s as simple as that.</p> <p>It is important for you to namespace your code so that it may be used by other developers without fear of colliding with other libraries.</p> <p>One recommended way to use namespaces is outlined in <a href="https://www.php-fig.org/psr/psr-4/">PSR-4</a>, which aims to provide a standard file, class and namespace convention to allow plug-and-play code.</p> <p>In October 2014 the PHP-FIG deprecated the previous autoloading standard: <a href="https://www.php-fig.org/psr/psr-0/">PSR-0</a>. Both PSR-0 and PSR-4 are still perfectly usable. The latter requires PHP 5.3, so many PHP 5.2-only projects implement PSR-0.</p> <p>If you’re going to use an autoloader standard for a new application or package, look into PSR-4.</p> <ul> <li><a href="https://www.php.net/language.namespaces">Read about Namespaces</a></li> <li><a href="https://www.php-fig.org/psr/psr-0/">Read about PSR-0</a></li> <li><a href="https://www.php-fig.org/psr/psr-4/">Read about PSR-4</a></li> </ul> </section> <section class="chapter" id="standard_php_library"> <h2 id="standard_php_library_title">Standard PHP Library</h2> <p>The Standard PHP Library (SPL) is packaged with PHP and provides a collection of classes and interfaces. It is made up primarily of commonly needed datastructure classes (stack, queue, heap, and so on), and iterators which can traverse over these datastructures or your own classes which implement SPL interfaces.</p> <ul> <li><a href="https://www.php.net/book.spl">Read about the SPL</a></li> <li><a href="https://www.linkedin.com/learning/learning-the-standard-php-library?trk=lynda_redirect_learning">SPL video course on LinkedIn.com (paid)</a></li> </ul> </section> <section class="chapter" id="command_line_interface"> <h2 id="command_line_interface_title">Command Line Interface</h2> <p>PHP was created to write web applications, but is also useful for scripting command line interface (CLI) programs. Command line PHP programs can help automate common tasks like testing, deployment, and application administration.</p> <p>CLI PHP programs are powerful because you can use your app’s code directly without having to create and secure a web GUI for it. Just be sure <strong>not</strong> to put your CLI PHP scripts in your public web root!</p> <p>Try running PHP from your command line:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="gp">></span><span class="w"> </span>php <span class="nt">-i</span></code></pre></figure> <p>The <code class="language-plaintext highlighter-rouge">-i</code> option will print your PHP configuration just like the <a href="https://www.php.net/function.phpinfo"><code class="language-plaintext highlighter-rouge">phpinfo()</code></a> function.</p> <p>The <code class="language-plaintext highlighter-rouge">-a</code> option provides an interactive shell, similar to ruby’s IRB or python’s interactive shell. There are a number of other useful <a href="https://www.php.net/features.commandline.options">command line options</a>, too.</p> <p>Let’s write a simple “Hello, $name” CLI program. To try it out, create a file named <code class="language-plaintext highlighter-rouge">hello.php</code>, as below.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$argc</span> <span class="o">!==</span> <span class="mi">2</span><span class="p">)</span> <span class="p">{</span> <span class="k">echo</span> <span class="s2">"Usage: php hello.php <name>"</span> <span class="mf">.</span> <span class="kc">PHP_EOL</span><span class="p">;</span> <span class="k">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="p">}</span> <span class="nv">$name</span> <span class="o">=</span> <span class="nv">$argv</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span> <span class="k">echo</span> <span class="s2">"Hello, </span><span class="nv">$name</span><span class="s2">"</span> <span class="mf">.</span> <span class="kc">PHP_EOL</span><span class="p">;</span></code></pre></figure> <p>PHP sets up two special variables based on the arguments your script is run with. <a href="https://www.php.net/reserved.variables.argc"><code class="language-plaintext highlighter-rouge">$argc</code></a> is an integer variable containing the argument <em>count</em> and <a href="https://www.php.net/reserved.variables.argv"><code class="language-plaintext highlighter-rouge">$argv</code></a> is an array variable containing each argument’s <em>value</em>. The first argument is always the name of your PHP script file, in this case <code class="language-plaintext highlighter-rouge">hello.php</code>.</p> <p>The <code class="language-plaintext highlighter-rouge">exit()</code> expression is used with a non-zero number to let the shell know that the command failed. Commonly used exit codes can be found <a href="https://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits">here</a>.</p> <p>To run our script, above, from the command line:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="gp">></span><span class="w"> </span>php hello.php <span class="gp">Usage: php hello.php <name></span><span class="w"> </span><span class="gp">></span><span class="w"> </span>php hello.php world <span class="go">Hello, world</span></code></pre></figure> <ul> <li><a href="https://www.php.net/manual/en/features.commandline.php">Learn about running PHP from the command line</a></li> </ul> </section> <section class="chapter" id="xdebug"> <h2 id="xdebug_title">Xdebug</h2> <p>One of the most useful tools in software development is a proper debugger. It allows you to trace the execution of your code and monitor the contents of the stack. Xdebug, PHP’s debugger, can be utilized by various IDEs to provide Breakpoints and stack inspection. It can also allow tools like PHPUnit and KCacheGrind to perform code coverage analysis and code profiling.</p> <p>If you find yourself in a bind, willing to resort to <code class="language-plaintext highlighter-rouge">var_dump()</code>/<code class="language-plaintext highlighter-rouge">print_r()</code>, and you still can’t find the solution - maybe you need to use the debugger.</p> <p><a href="https://xdebug.org/docs/install">Installing Xdebug</a> can be tricky, but one of its most important features is “Remote Debugging” - if you develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you will want to enable right away.</p> <p>Traditionally, you will modify your Apache VHost or .htaccess file with these values:</p> <figure class="highlight"><pre><code class="language-ini" data-lang="ini"><span class="err">php_value</span> <span class="err">xdebug.remote_host</span> <span class="err">192.168.?.?</span> <span class="err">php_value</span> <span class="err">xdebug.remote_port</span> <span class="err">9000</span></code></pre></figure> <p>The “remote host” and “remote port” will correspond to your local computer and the port that you configure your IDE to listen on. Then it’s just a matter of putting your IDE into “listen for connections” mode, and loading the URL:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>http://your-website.example.com/index.php?XDEBUG_SESSION_START=1 </code></pre></div></div> <p>Your IDE will now intercept the current state as the script executes, allowing you to set breakpoints and probe the values in memory.</p> <p>Graphical debuggers make it very easy to step through code, inspect variables, and eval code against the live runtime. Many IDEs have built-in or plugin-based support for graphical debugging with Xdebug. MacGDBp is a free, open-source, stand-alone Xdebug GUI for macOS.</p> <ul> <li><a href="https://xdebug.org/docs/">Learn more about Xdebug</a></li> <li><a href="https://www.bluestatic.org/software/macgdbp/">Learn more about MacGDBp</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="dependency_management"> <h1 id="dependency_management_title">Dependency Management</h1> <p>There are a ton of PHP libraries, frameworks, and components to choose from. Your project will likely use several of them — these are project dependencies. Until recently, PHP did not have a good way to manage these project dependencies. Even if you managed them manually, you still had to worry about autoloaders. That is no longer an issue.</p> <p>Currently there are two major package management systems for PHP - <a href="/#composer_and_packagist">Composer</a> and <a href="/#pear">PEAR</a>. Composer is currently the most popular package manager for PHP, however for a long time PEAR was the primary package manager in use. Knowing PEAR’s history is a good idea, since you may still find references to it even if you never use it.</p> </section> <section class="chapter" id="composer_and_packagist"> <h2 id="composer_and_packagist_title">Composer and Packagist</h2> <p>Composer is the recommended dependency manager for PHP. List your project’s dependencies in a <code class="language-plaintext highlighter-rouge">composer.json</code> file and, 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.</p> <p>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 <a href="https://packagist.org/">Packagist</a>, the official repository for Composer-compatible PHP libraries.</p> <h3 id="how-to-install-composer">How to Install Composer</h3> <p>The safest way to download composer is by <a href="https://getcomposer.org/download/">following the official instructions</a>. This will verify the installer is not corrupt or tampered with. The installer installs a <code class="language-plaintext highlighter-rouge">composer.phar</code> binary in your <em>current working directory</em>.</p> <p>We recommend installing Composer <em>globally</em> (e.g. a single copy in <code class="language-plaintext highlighter-rouge">/usr/local/bin</code>). To do so, run this command next:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="go">mv composer.phar /usr/local/bin/composer</span></code></pre></figure> <p><strong>Note:</strong> If the above fails due to permissions, prefix with <code class="language-plaintext highlighter-rouge">sudo</code>.</p> <p>To run a locally installed Composer you’d use <code class="language-plaintext highlighter-rouge">php composer.phar</code>, globally it’s simply <code class="language-plaintext highlighter-rouge">composer</code>.</p> <h4 id="installing-on-windows">Installing on Windows</h4> <p>For Windows users the easiest way to get up and running is to use the <a href="https://getcomposer.org/Composer-Setup.exe">ComposerSetup</a> installer, which performs a global install and sets up your <code class="language-plaintext highlighter-rouge">$PATH</code> so that you can just call <code class="language-plaintext highlighter-rouge">composer</code> from any directory in your command line.</p> <h3 id="how-to-define-and-install-dependencies">How to Define and Install Dependencies</h3> <p>Composer keeps track of your project’s dependencies in a file called <code class="language-plaintext highlighter-rouge">composer.json</code>. You can manage it by hand if you like, or use Composer itself. The <code class="language-plaintext highlighter-rouge">composer require</code> command adds a project dependency and if you don’t have a <code class="language-plaintext highlighter-rouge">composer.json</code> file, one will be created. Here’s an example that adds <a href="https://twig.symfony.com/">Twig</a> as a dependency of your project.</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="go">composer require twig/twig:^2.0</span></code></pre></figure> <p>Alternatively, the <code class="language-plaintext highlighter-rouge">composer init</code> command will guide you through creating a full <code class="language-plaintext highlighter-rouge">composer.json</code> file for your project. Either way, once you’ve created your <code class="language-plaintext highlighter-rouge">composer.json</code> file you can tell Composer to download and install your dependencies into the <code class="language-plaintext highlighter-rouge">vendor/</code> directory. This also applies to projects you’ve downloaded that already provide a <code class="language-plaintext highlighter-rouge">composer.json</code> file:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="go">composer install</span></code></pre></figure> <p>Next, add this line to your application’s primary PHP file; this will tell PHP to use Composer’s autoloader for your project dependencies.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="k">require</span> <span class="s1">'vendor/autoload.php'</span><span class="p">;</span></code></pre></figure> <p>Now you can use your project dependencies, and they’ll be autoloaded on demand.</p> <h3 id="updating-your-dependencies">Updating your dependencies</h3> <p>Composer creates a file called <code class="language-plaintext highlighter-rouge">composer.lock</code> which stores the exact version of each package it downloaded when you first ran <code class="language-plaintext highlighter-rouge">composer install</code>. If you share your project with others, ensure the <code class="language-plaintext highlighter-rouge">composer.lock</code> file is included, so that when they run <code class="language-plaintext highlighter-rouge">composer install</code> they’ll get the same versions as you. To update your dependencies, run <code class="language-plaintext highlighter-rouge">composer update</code>. Don’t use <code class="language-plaintext highlighter-rouge">composer update</code> when deploying, only <code class="language-plaintext highlighter-rouge">composer install</code>, otherwise you may end up with different package versions on production.</p> <p>This is most useful when you define your version requirements flexibly. For instance, a version requirement of <code class="language-plaintext highlighter-rouge">~1.8</code> means “anything newer than <code class="language-plaintext highlighter-rouge">1.8.0</code>, but less than <code class="language-plaintext highlighter-rouge">2.0.x-dev</code>”. You can also use the <code class="language-plaintext highlighter-rouge">*</code> wildcard as in <code class="language-plaintext highlighter-rouge">1.8.*</code>. Now Composer’s <code class="language-plaintext highlighter-rouge">composer update</code> command will upgrade all your dependencies to the newest version that fits the restrictions you define.</p> <h3 id="update-notifications">Update Notifications</h3> <p>To receive notifications about new version releases you can sign up for <a href="https://libraries.io/">libraries.io</a>, a web service that can monitor dependencies and send you alerts on updates.</p> <h3 id="checking-your-dependencies-for-security-issues">Checking your dependencies for security issues</h3> <p>The <a href="https://github.com/fabpot/local-php-security-checker">Local PHP Security Checker</a> is a command-line tool, which will examine your <code class="language-plaintext highlighter-rouge">composer.lock</code> file and tell you if you need to update any of your dependencies.</p> <h3 id="handling-global-dependencies-with-composer">Handling global dependencies with Composer</h3> <p>Composer can also handle global dependencies and their binaries. Usage is straight-forward, all you need to do is prefix your command with <code class="language-plaintext highlighter-rouge">global</code>. If for example you wanted to install PHPUnit and have it available globally, you’d run the following command:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="go">composer global require phpunit/phpunit</span></code></pre></figure> <p>This will create a <code class="language-plaintext highlighter-rouge">~/.composer</code> folder where your global dependencies reside. To have the installed packages’ binaries available everywhere, you’d then add the <code class="language-plaintext highlighter-rouge">~/.composer/vendor/bin</code> folder to your <code class="language-plaintext highlighter-rouge">$PATH</code> variable.</p> <ul> <li><a href="https://getcomposer.org/doc/00-intro.md">Learn about Composer</a></li> </ul> </section> <section class="chapter" id="pear"> <h2 id="pear_title">PEAR</h2> <p>A veteran package manager that some PHP developers enjoy is <a href="https://pear.php.net/">PEAR</a>. It behaves similarly to Composer, but has some notable differences.</p> <p>PEAR requires each package to have a specific structure, which means that the author of the package must prepare it for usage with PEAR. Using a project which was not prepared to work with PEAR is not possible.</p> <p>PEAR installs packages globally, which means after installing them once they are available to all projects on that server. This can be good if many projects rely on the same package with the same version but might lead to problems if version conflicts between two projects arise.</p> <h3 id="how-to-install-pear">How to install PEAR</h3> <p>You can install PEAR by downloading the <code class="language-plaintext highlighter-rouge">.phar</code> installer and executing it. The PEAR documentation has detailed <a href="https://pear.php.net/manual/installation.getting.php">install instructions</a> for every operating system.</p> <p>If you are using Linux, you can also have a look at your distribution package manager. Debian and Ubuntu, for example, have an apt <code class="language-plaintext highlighter-rouge">php-pear</code> package.</p> <h3 id="how-to-install-a-package">How to install a package</h3> <p>If the package is listed on the <a href="https://pear.php.net/packages.php">PEAR packages list</a>, you can install it by specifying the official name:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="go">pear install foo</span></code></pre></figure> <p>If the package is hosted on another channel, you need to <code class="language-plaintext highlighter-rouge">discover</code> the channel first and also specify it when installing. See the <a href="https://pear.php.net/manual/guide.users.commandline.channels.php">Using channel docs</a> for more information on this topic.</p> <ul> <li><a href="https://pear.php.net/">Learn about PEAR</a></li> </ul> <h3 id="handling-pear-dependencies-with-composer">Handling PEAR dependencies with Composer</h3> <p>If you are already using <a href="/#composer_and_packagist">Composer</a> and you would like to install some PEAR code too, you can use Composer to handle your PEAR dependencies. PEAR repositories are no longer directly supported by Composer version 2, so you must manually add a repository to install PEAR packages:</p> <figure class="highlight"><pre><code class="language-json" data-lang="json"><span class="p">{</span><span class="w"> </span><span class="nl">"repositories"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"package"</span><span class="p">,</span><span class="w"> </span><span class="nl">"package"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"pear2/pear2-http-request"</span><span class="p">,</span><span class="w"> </span><span class="nl">"version"</span><span class="p">:</span><span class="w"> </span><span class="s2">"2.5.1"</span><span class="p">,</span><span class="w"> </span><span class="nl">"dist"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"url"</span><span class="p">:</span><span class="w"> </span><span class="s2">"https://github.com/pear2/HTTP_Request/archive/refs/heads/master.zip"</span><span class="p">,</span><span class="w"> </span><span class="nl">"type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"zip"</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="p">],</span><span class="w"> </span><span class="nl">"require"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"pear2/pear2-http-request"</span><span class="p">:</span><span class="w"> </span><span class="s2">"*"</span><span class="w"> </span><span class="p">},</span><span class="w"> </span><span class="nl">"autoload"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"psr-4"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="nl">"PEAR2\\HTTP\\"</span><span class="p">:</span><span class="w"> </span><span class="s2">"vendor/pear2/pear2-http-request/src/HTTP/"</span><span class="p">}</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="p">}</span></code></pre></figure> <p>The first section <code class="language-plaintext highlighter-rouge">"repositories"</code> will be used to let Composer know it should “initialize” (or “discover” in PEAR terminology) the pear repo. Then the <code class="language-plaintext highlighter-rouge">require</code> section will prefix the package name like this:</p> <blockquote> <p>pear-channel/package</p> </blockquote> <p>The “pear” prefix is hardcoded to avoid any conflicts, as a pear channel could be the same as another packages vendor name for example, then the channel short name (or full URL) can be used to reference which channel the package is in.</p> <p>When this code is installed it will be available in your vendor directory and automatically available through the Composer autoloader:</p> <blockquote> <p>vendor/pear2/pear2-http-request/pear2/HTTP/Request.php</p> </blockquote> <p>To use this PEAR package simply reference it like so:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="k">require</span> <span class="k">__DIR__</span> <span class="mf">.</span> <span class="s1">'/vendor/autoload.php'</span><span class="p">;</span> <span class="kn">use</span> <span class="nc">PEAR2\HTTP\Request</span><span class="p">;</span> <span class="nv">$request</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Request</span><span class="p">();</span></code></pre></figure> <ul> <li><a href="https://getcomposer.org/doc/05-repositories.md">Learn more about using repositories with Composer</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="coding_practices"> <h1 id="coding_practices_title">Coding Practices</h1> </section> <section class="chapter" id="the_basics"> <h2 id="the_basics_title">The Basics</h2> <p>PHP is a vast language that allows coders of all levels the ability to produce code not only quickly, but efficiently. However, while advancing through the language, we often forget the basics that we first learnt (or overlooked) in favor of short cuts and/or bad habits. To help combat this common issue, this section is aimed at reminding coders of the basic coding practices within PHP.</p> <ul> <li>Continue reading on <a href="/pages/The-Basics.html">The Basics</a></li> </ul> </section> <section class="chapter" id="date_and_time"> <h2 id="date_and_time_title">Date and Time</h2> <p>PHP has a class named DateTime to help you when reading, writing, comparing or calculating with date and time. There are many date and time related functions in PHP besides DateTime, but it provides nice object-oriented interface to most common uses. DateTime can handle time zones, but that is outside the scope of this short introduction.</p> <p>To start working with DateTime, convert raw date and time string to an object with <code class="language-plaintext highlighter-rouge">createFromFormat()</code> factory method or do <code class="language-plaintext highlighter-rouge">new DateTime</code> to get the current date and time. Use <code class="language-plaintext highlighter-rouge">format()</code> method to convert DateTime back to a string for output.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="nv">$raw</span> <span class="o">=</span> <span class="s1">'22. 11. 1968'</span><span class="p">;</span> <span class="nv">$start</span> <span class="o">=</span> <span class="nc">DateTime</span><span class="o">::</span><span class="nf">createFromFormat</span><span class="p">(</span><span class="s1">'d. m. Y'</span><span class="p">,</span> <span class="nv">$raw</span><span class="p">);</span> <span class="k">echo</span> <span class="s1">'Start date: '</span> <span class="mf">.</span> <span class="nv">$start</span><span class="o">-></span><span class="nf">format</span><span class="p">(</span><span class="s1">'Y-m-d'</span><span class="p">)</span> <span class="mf">.</span> <span class="kc">PHP_EOL</span><span class="p">;</span></code></pre></figure> <p>Calculating with DateTime is possible with the DateInterval class. DateTime has methods like <code class="language-plaintext highlighter-rouge">add()</code> and <code class="language-plaintext highlighter-rouge">sub()</code> that take a DateInterval as an argument. Do not write code that expects the same number of seconds in every day. Both daylight saving and time zone alterations will break that assumption. Use date intervals instead. To calculate date difference use the <code class="language-plaintext highlighter-rouge">diff()</code> method. It will return new DateInterval, which is super easy to display.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="c1">// create a copy of $start and add one month and 6 days</span> <span class="nv">$end</span> <span class="o">=</span> <span class="k">clone</span> <span class="nv">$start</span><span class="p">;</span> <span class="nv">$end</span><span class="o">-></span><span class="nf">add</span><span class="p">(</span><span class="k">new</span> <span class="nc">DateInterval</span><span class="p">(</span><span class="s1">'P1M6D'</span><span class="p">));</span> <span class="nv">$diff</span> <span class="o">=</span> <span class="nv">$end</span><span class="o">-></span><span class="nf">diff</span><span class="p">(</span><span class="nv">$start</span><span class="p">);</span> <span class="k">echo</span> <span class="s1">'Difference: '</span> <span class="mf">.</span> <span class="nv">$diff</span><span class="o">-></span><span class="nf">format</span><span class="p">(</span><span class="s1">'%m month, %d days (total: %a days)'</span><span class="p">)</span> <span class="mf">.</span> <span class="kc">PHP_EOL</span><span class="p">;</span> <span class="c1">// Difference: 1 month, 6 days (total: 37 days)</span></code></pre></figure> <p>You can use standard comparisons on DateTime objects:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$start</span> <span class="o"><</span> <span class="nv">$end</span><span class="p">)</span> <span class="p">{</span> <span class="k">echo</span> <span class="s2">"Start is before the end!"</span> <span class="mf">.</span> <span class="kc">PHP_EOL</span><span class="p">;}</span></code></pre></figure> <p>One last example to demonstrate the DatePeriod class. It is used to iterate over recurring events. It can take two DateTime objects, start and end, and the interval for which it will return all events in between.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="c1">// output all thursdays between $start and $end</span> <span class="nv">$periodInterval</span> <span class="o">=</span> <span class="nc">DateInterval</span><span class="o">::</span><span class="nf">createFromDateString</span><span class="p">(</span><span class="s1">'first thursday'</span><span class="p">);</span> <span class="nv">$periodIterator</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DatePeriod</span><span class="p">(</span><span class="nv">$start</span><span class="p">,</span> <span class="nv">$periodInterval</span><span class="p">,</span> <span class="nv">$end</span><span class="p">,</span> <span class="nc">DatePeriod</span><span class="o">::</span><span class="no">EXCLUDE_START_DATE</span><span class="p">);</span> <span class="k">foreach</span> <span class="p">(</span><span class="nv">$periodIterator</span> <span class="k">as</span> <span class="nv">$date</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// output each date in the period</span> <span class="k">echo</span> <span class="nv">$date</span><span class="o">-></span><span class="nf">format</span><span class="p">(</span><span class="s1">'Y-m-d'</span><span class="p">)</span> <span class="mf">.</span> <span class="s1">' '</span><span class="p">;</span> <span class="p">}</span></code></pre></figure> <p>A popular PHP API extension is <a href="https://carbon.nesbot.com/">Carbon</a>. 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.</p> <ul> <li><a href="https://www.php.net/book.datetime">Read about DateTime</a></li> <li><a href="https://www.php.net/function.date">Read about date formatting</a> (accepted date format string options)</li> </ul> </section> <section class="chapter" id="design_patterns"> <h2 id="design_patterns_title">Design Patterns</h2> <p>When you are building your application it is helpful to use common patterns in your code and common patterns for the overall structure of your project. Using common patterns is helpful because it makes it much easier to manage your code and lets other developers quickly understand how everything fits together.</p> <p>If you use a framework then most of the higher level code and project structure will be based on that framework, so a lot of the pattern decisions are made for you. But it is still up to you to pick out the best patterns to follow in the 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.</p> <p>You can learn more about PHP design patterns and see working examples at:</p> <ul> <li><a href="https://refactoring.guru/design-patterns/php">https://refactoring.guru/design-patterns/php</a></li> <li><a href="https://designpatternsphp.readthedocs.io/en/latest/">https://designpatternsphp.readthedocs.io/</a> (<a href="https://www.computer-pdf.com/web-programming/php/924-tutorial-designpatternsphp-documentation.html">PDF download</a>)</li> </ul> </section> <section class="chapter" id="php_and_utf8"> <h2 id="php_and_utf8_title">Working with UTF-8</h2> <p><em>This section was originally written by <a href="https://alexcabal.com/">Alex Cabal</a> over at <a href="https://phpbestpractices.org/#utf-8">PHP Best Practices</a> and has been used as the basis for our own UTF-8 advice</em>.</p> <h3 id="theres-no-one-liner-be-careful-detailed-and-consistent">There’s no one-liner. Be careful, detailed, and consistent.</h3> <p>Right now PHP does not support Unicode at a low level. There are ways to ensure that UTF-8 strings are processed OK, but it’s not easy, and it requires digging in to almost all levels of the web app, from HTML to SQL to PHP. We’ll aim for a brief, practical summary.</p> <h3 id="utf-8-at-the-php-level">UTF-8 at the PHP level</h3> <p>The basic string operations, like concatenating two strings and assigning strings to variables, don’t need anything special for UTF-8. However, most string functions, like <code class="language-plaintext highlighter-rouge">strpos()</code> and <code class="language-plaintext highlighter-rouge">strlen()</code>, do need special consideration. These functions often have an <code class="language-plaintext highlighter-rouge">mb_*</code> counterpart: for example, <code class="language-plaintext highlighter-rouge">mb_strpos()</code> and <code class="language-plaintext highlighter-rouge">mb_strlen()</code>. These <code class="language-plaintext highlighter-rouge">mb_*</code> strings are made available to you via the <a href="https://www.php.net/book.mbstring">Multibyte String Extension</a>, and are specifically designed to operate on Unicode strings.</p> <p>You must use the <code class="language-plaintext highlighter-rouge">mb_*</code> functions whenever you operate on a Unicode string. For example, if you use <code class="language-plaintext highlighter-rouge">substr()</code> on a UTF-8 string, there’s a good chance the result will include some garbled half-characters. The correct function to use would be the multibyte counterpart, <code class="language-plaintext highlighter-rouge">mb_substr()</code>.</p> <p>The hard part is remembering to use the <code class="language-plaintext highlighter-rouge">mb_*</code> functions at all times. If you forget even just once, your Unicode string has a chance of being garbled during further processing.</p> <p>Not all string functions have an <code class="language-plaintext highlighter-rouge">mb_*</code> counterpart. If there isn’t one for what you want to do, then you might be out of luck.</p> <p>You should use the <code class="language-plaintext highlighter-rouge">mb_internal_encoding()</code> function at the top of every PHP script you write (or at the top of your global include script), and the <code class="language-plaintext highlighter-rouge">mb_http_output()</code> function right after it if your script is outputting to a browser. Explicitly defining the encoding of your strings in every script will save you a lot of headaches down the road.</p> <p>Additionally, many PHP functions that operate on strings have an optional parameter letting you specify the character encoding. You should always explicitly indicate UTF-8 when given the option. For example, <code class="language-plaintext highlighter-rouge">htmlentities()</code> has an option for character encoding, and you should always specify UTF-8 if dealing with such strings. Note that as of PHP 5.4.0, UTF-8 is the default encoding for <code class="language-plaintext highlighter-rouge">htmlentities()</code> and <code class="language-plaintext highlighter-rouge">htmlspecialchars()</code>.</p> <p>Finally, If you are building a distributed application and cannot be certain that the <code class="language-plaintext highlighter-rouge">mbstring</code> extension will be enabled, then consider using the <a href="https://packagist.org/packages/symfony/polyfill-mbstring">symfony/polyfill-mbstring</a> Composer package. This will use <code class="language-plaintext highlighter-rouge">mbstring</code> if it is available, and fall back to non UTF-8 functions if not.</p> <h3 id="utf-8-at-the-database-level">UTF-8 at the Database level</h3> <p>If your PHP script accesses MySQL, there’s a chance your strings could be stored as non-UTF-8 strings in the database even if you follow all of the precautions above.</p> <p>To make sure your strings go from PHP to MySQL as UTF-8, make sure your database and tables are all set to the <code class="language-plaintext highlighter-rouge">utf8mb4</code> character set and collation, and that you use the <code class="language-plaintext highlighter-rouge">utf8mb4</code> character set in the PDO connection string. See example code below. This is <em>critically important</em>.</p> <p>Note that you must use the <code class="language-plaintext highlighter-rouge">utf8mb4</code> character set for complete UTF-8 support, not the <code class="language-plaintext highlighter-rouge">utf8</code> character set! See Further Reading for why.</p> <h3 id="utf-8-at-the-browser-level">UTF-8 at the browser level</h3> <p>Use the <code class="language-plaintext highlighter-rouge">mb_http_output()</code> function to ensure that your PHP script outputs UTF-8 strings to your browser.</p> <p>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:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="nb">header</span><span class="p">(</span><span class="s1">'Content-Type: text/html; charset=UTF-8'</span><span class="p">)</span></code></pre></figure> <p>The historic approach to doing that was to include the <a href="http://htmlpurifier.org/docs/enduser-utf8.html">charset <code class="language-plaintext highlighter-rouge"><meta></code> tag</a> in your page’s <code class="language-plaintext highlighter-rouge"><head></code> tag.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="c1">// Tell PHP that we're using UTF-8 strings until the end of the script</span> <span class="nb">mb_internal_encoding</span><span class="p">(</span><span class="s1">'UTF-8'</span><span class="p">);</span> <span class="nv">$utf_set</span> <span class="o">=</span> <span class="nb">ini_set</span><span class="p">(</span><span class="s1">'default_charset'</span><span class="p">,</span> <span class="s1">'utf-8'</span><span class="p">);</span> <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nv">$utf_set</span><span class="p">)</span> <span class="p">{</span> <span class="k">throw</span> <span class="k">new</span> <span class="nc">Exception</span><span class="p">(</span><span class="s1">'could not set default_charset to utf-8, please ensure it\'s set on your system!'</span><span class="p">);</span> <span class="p">}</span> <span class="c1">// Tell PHP that we'll be outputting UTF-8 to the browser</span> <span class="nb">mb_http_output</span><span class="p">(</span><span class="s1">'UTF-8'</span><span class="p">);</span> <span class="c1">// Our UTF-8 test string</span> <span class="nv">$string</span> <span class="o">=</span> <span class="s1">'Êl síla erin lû e-govaned vîn.'</span><span class="p">;</span> <span class="c1">// Transform the string in some way with a multibyte function</span> <span class="c1">// Note how we cut the string at a non-Ascii character for demonstration purposes</span> <span class="nv">$string</span> <span class="o">=</span> <span class="nb">mb_substr</span><span class="p">(</span><span class="nv">$string</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">15</span><span class="p">);</span> <span class="c1">// Connect to a database to store the transformed string</span> <span class="c1">// See the PDO example in this document for more information</span> <span class="c1">// Note the `charset=utf8mb4` in the Data Source Name (DSN)</span> <span class="nv">$link</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">PDO</span><span class="p">(</span> <span class="s1">'mysql:host=your-hostname;dbname=your-db;charset=utf8mb4'</span><span class="p">,</span> <span class="s1">'your-username'</span><span class="p">,</span> <span class="s1">'your-password'</span><span class="p">,</span> <span class="k">array</span><span class="p">(</span> <span class="no">PDO</span><span class="o">::</span><span class="no">ATTR_ERRMODE</span> <span class="o">=></span> <span class="no">PDO</span><span class="o">::</span><span class="no">ERRMODE_EXCEPTION</span><span class="p">,</span> <span class="no">PDO</span><span class="o">::</span><span class="no">ATTR_PERSISTENT</span> <span class="o">=></span> <span class="kc">false</span> <span class="p">)</span> <span class="p">);</span> <span class="c1">// Store our transformed string as UTF-8 in our database</span> <span class="c1">// Your DB and tables are in the utf8mb4 character set and collation, right?</span> <span class="nv">$handle</span> <span class="o">=</span> <span class="nv">$link</span><span class="o">-></span><span class="nf">prepare</span><span class="p">(</span><span class="s1">'insert into ElvishSentences (Id, Body, Priority) values (default, :body, :priority)'</span><span class="p">);</span> <span class="nv">$handle</span><span class="o">-></span><span class="nf">bindParam</span><span class="p">(</span><span class="s1">':body'</span><span class="p">,</span> <span class="nv">$string</span><span class="p">,</span> <span class="no">PDO</span><span class="o">::</span><span class="no">PARAM_STR</span><span class="p">);</span> <span class="nv">$priority</span> <span class="o">=</span> <span class="mi">45</span><span class="p">;</span> <span class="nv">$handle</span><span class="o">-></span><span class="nf">bindParam</span><span class="p">(</span><span class="s1">':priority'</span><span class="p">,</span> <span class="nv">$priority</span><span class="p">,</span> <span class="no">PDO</span><span class="o">::</span><span class="no">PARAM_INT</span><span class="p">);</span> <span class="c1">// explicitly tell pdo to expect an int</span> <span class="nv">$handle</span><span class="o">-></span><span class="nf">execute</span><span class="p">();</span> <span class="c1">// Retrieve the string we just stored to prove it was stored correctly</span> <span class="nv">$handle</span> <span class="o">=</span> <span class="nv">$link</span><span class="o">-></span><span class="nf">prepare</span><span class="p">(</span><span class="s1">'select * from ElvishSentences where Id = :id'</span><span class="p">);</span> <span class="nv">$id</span> <span class="o">=</span> <span class="mi">7</span><span class="p">;</span> <span class="nv">$handle</span><span class="o">-></span><span class="nf">bindParam</span><span class="p">(</span><span class="s1">':id'</span><span class="p">,</span> <span class="nv">$id</span><span class="p">,</span> <span class="no">PDO</span><span class="o">::</span><span class="no">PARAM_INT</span><span class="p">);</span> <span class="nv">$handle</span><span class="o">-></span><span class="nf">execute</span><span class="p">();</span> <span class="c1">// Store the result into an object that we'll output later in our HTML</span> <span class="c1">// This object won't kill your memory because it fetches the data Just-In-Time to</span> <span class="nv">$result</span> <span class="o">=</span> <span class="nv">$handle</span><span class="o">-></span><span class="nf">fetchAll</span><span class="p">(</span><span class="err">\</span><span class="no">PDO</span><span class="o">::</span><span class="no">FETCH_OBJ</span><span class="p">);</span> <span class="c1">// An example wrapper to allow you to escape data to html</span> <span class="k">function</span> <span class="n">escape_to_html</span><span class="p">(</span><span class="nv">$dirty</span><span class="p">){</span> <span class="k">echo</span> <span class="nb">htmlspecialchars</span><span class="p">(</span><span class="nv">$dirty</span><span class="p">,</span> <span class="no">ENT_QUOTES</span><span class="p">,</span> <span class="s1">'UTF-8'</span><span class="p">);</span> <span class="p">}</span> <span class="nb">header</span><span class="p">(</span><span class="s1">'Content-Type: text/html; charset=UTF-8'</span><span class="p">);</span> <span class="c1">// Unnecessary if your default_charset is set to utf-8 already</span> <span class="cp">?><!doctype html></span> <span class="nt"><html></span> <span class="nt"><head></span> <span class="nt"><meta</span> <span class="na">charset=</span><span class="s">"UTF-8"</span><span class="nt">></span> <span class="nt"><title></span>UTF-8 test page<span class="nt"></title></span> <span class="nt"></head></span> <span class="nt"><body></span> <span class="cp"><?php</span> <span class="k">foreach</span><span class="p">(</span><span class="nv">$result</span> <span class="k">as</span> <span class="nv">$row</span><span class="p">){</span> <span class="nf">escape_to_html</span><span class="p">(</span><span class="nv">$row</span><span class="o">-></span><span class="nc">Body</span><span class="p">);</span> <span class="c1">// This should correctly output our transformed UTF-8 string to the browser</span> <span class="p">}</span> <span class="cp">?></span> <span class="nt"></body></span> <span class="nt"></html></span></code></pre></figure> <h3 id="further-reading">Further reading</h3> <ul> <li><a href="https://www.php.net/language.operators.string">PHP Manual: String Operations</a></li> <li><a href="https://www.php.net/ref.strings">PHP Manual: String Functions</a> <ul> <li><a href="https://www.php.net/function.strpos"><code class="language-plaintext highlighter-rouge">strpos()</code></a></li> <li><a href="https://www.php.net/function.strlen"><code class="language-plaintext highlighter-rouge">strlen()</code></a></li> <li><a href="https://www.php.net/function.substr"><code class="language-plaintext highlighter-rouge">substr()</code></a></li> </ul> </li> <li><a href="https://www.php.net/ref.mbstring">PHP Manual: Multibyte String Functions</a> <ul> <li><a href="https://www.php.net/function.mb-strpos"><code class="language-plaintext highlighter-rouge">mb_strpos()</code></a></li> <li><a href="https://www.php.net/function.mb-strlen"><code class="language-plaintext highlighter-rouge">mb_strlen()</code></a></li> <li><a href="https://www.php.net/function.mb-substr"><code class="language-plaintext highlighter-rouge">mb_substr()</code></a></li> <li><a href="https://www.php.net/function.mb-internal-encoding"><code class="language-plaintext highlighter-rouge">mb_internal_encoding()</code></a></li> <li><a href="https://www.php.net/function.mb-http-output"><code class="language-plaintext highlighter-rouge">mb_http_output()</code></a></li> <li><a href="https://www.php.net/function.htmlentities"><code class="language-plaintext highlighter-rouge">htmlentities()</code></a></li> <li><a href="https://www.php.net/function.htmlspecialchars"><code class="language-plaintext highlighter-rouge">htmlspecialchars()</code></a></li> </ul> </li> <li><a href="https://stackoverflow.com/questions/571694/what-factors-make-php-unicode-incompatible">Stack Overflow: What factors make PHP Unicode-incompatible?</a></li> <li><a href="https://stackoverflow.com/questions/140728/best-practices-in-php-and-mysql-with-international-strings">Stack Overflow: Best practices in PHP and MySQL with international strings</a></li> <li><a href="https://mathiasbynens.be/notes/mysql-utf8mb4">How to support full Unicode in MySQL databases</a></li> <li><a href="https://www.sitepoint.com/bringing-unicode-to-php-with-portable-utf8/">Bringing Unicode to PHP with Portable UTF-8</a></li> <li><a href="https://stackoverflow.com/questions/8218230/php-domdocument-loadhtml-not-encoding-utf-8-correctly">Stack Overflow: DOMDocument loadHTML does not encode UTF-8 correctly</a></li> </ul> </section> <section class="chapter" id="i18n_l10n"> <h2 id="i18n_l10n_title">Internationalization (i18n) and Localization (l10n)</h2> <p><em>Disclaimer for newcomers: i18n and l10n are numeronyms, a kind of abbreviation where numbers are used to shorten words - in our case, internationalization becomes i18n and localization, l10n.</em></p> <p>First of all, we need to define those two similar concepts and other related things:</p> <ul> <li><strong>Internationalization</strong> is when you organize your code so it can be adapted to different languages or regions without refactorings. This action is usually done once - preferably, at the beginning of the project, or else you will probably need some huge changes in the source!</li> <li><strong>Localization</strong> 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 are added, as they need to be available in all supported languages.</li> <li><strong>Pluralization</strong> 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 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. 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.</li> </ul> <h2 id="common-ways-to-implement">Common ways to implement</h2> <p>The easiest way to internationalize PHP software is by using array files and using those strings in templates, such as <code class="language-plaintext highlighter-rouge"><h1><?=$TRANS['title_about_page']?></h1></code>. 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, don’t try this if your project will contain more than a couple of pages.</p> <p>The most classic way and often taken as reference for i18n and l10n is a <a href="https://en.wikipedia.org/wiki/Gettext">Unix tool called <code class="language-plaintext highlighter-rouge">gettext</code></a>. It dates back to 1995 and is still a complete implementation for translating software. It is easy enough to get running, while 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.</p> <h3 id="other-tools">Other tools</h3> <p>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 PHP core, but here we list others for completion:</p> <ul> <li><a href="https://github.com/auraphp/Aura.Intl">aura/intl</a>: Provides internationalization (I18N) tools, specifically package-oriented per-locale message translation. It uses array formats for messages. Does not provide a message extractor, but does provide advanced message formatting via the <code class="language-plaintext highlighter-rouge">intl</code> extension (including pluralized messages).</li> <li><a href="https://github.com/php-gettext/Gettext">php-gettext/Gettext</a>: Gettext support with an OO interface; includes improved helper functions, powerful extractors for several file formats (some of them not supported natively by the <code class="language-plaintext highlighter-rouge">gettext</code> command), and can also export to other formats besides <code class="language-plaintext highlighter-rouge">.mo/.po</code> files. Can be useful if you need to integrate your translation files into other parts of the system, like a JavaScript interface.</li> <li><a href="https://symfony.com/components/Translation">symfony/translation</a>: 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 <code class="language-plaintext highlighter-rouge">strtr()</code> internally.</li> <li><a href="https://docs.laminas.dev/laminas-i18n/">laminas/laminas-i18n</a>: supports array and INI files, or Gettext formats. Implements a caching layer to save you from reading the filesystem every time. It also includes view helpers, and locale-aware input filters and validators. However, it has no message extractor.</li> </ul> <p>Other frameworks also include i18n modules, but those are not available outside of their codebases:</p> <ul> <li><a href="https://laravel.com/docs/master/localization">Laravel</a> supports basic array files, has no automatic extractor but includes a <code class="language-plaintext highlighter-rouge">@lang</code> helper for template files.</li> <li><a href="https://www.yiiframework.com/doc/guide/2.0/en/tutorial-i18n">Yii</a> supports array, Gettext, and database-based translation, and includes a messages extractor. It is backed by the <a href="https://www.php.net/manual/intro.intl.php"><code class="language-plaintext highlighter-rouge">Intl</code></a> extension, available since PHP 5.3, and based on the <a href="https://icu.unicode.org/">ICU project</a>; this enables Yii to run powerful replacements, like spelling out numbers, formatting dates, times, intervals, currency, and ordinals.</li> </ul> <p>If you decide to go for one of the libraries that provide no extractors, you may want to use the gettext formats, so you can use the original gettext toolchain (including Poedit) as described in the rest of the chapter.</p> <h2 id="gettext">Gettext</h2> <h3 id="installation">Installation</h3> <p>You might need to install Gettext and the related PHP library by using your package manager, like <code class="language-plaintext highlighter-rouge">apt-get</code> or <code class="language-plaintext highlighter-rouge">yum</code>. After installed, enable it by adding <code class="language-plaintext highlighter-rouge">extension=gettext.so</code> (Linux/Unix) or <code class="language-plaintext highlighter-rouge">extension=php_gettext.dll</code> (Windows) to your <code class="language-plaintext highlighter-rouge">php.ini</code>.</p> <p>Here we will also be using <a href="https://poedit.net">Poedit</a> to create translation files. You will probably find it in your system’s package manager; it is available for Unix, macOS, and Windows, and can be <a href="https://poedit.net/download">downloaded for free on their website</a> as well.</p> <h3 id="structure">Structure</h3> <h4 id="types-of-files">Types of files</h4> <p>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 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 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 will always have one pair of PO/MO files per language and region, but only one POT per domain.</p> <h3 id="domains">Domains</h3> <p>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 <em>domains</em>. They are, basically, named groups of POT/PO/MO files, where the filename is the said <em>translation domain</em>. 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. In <a href="https://symfony.com/components/Translation">Symfony</a> projects, for example, domains are used to separate the translation for validation messages.</p> <h4 id="locale-code">Locale code</h4> <p>A locale is simply a code that identifies one version of a language. It is defined following the <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes">ISO 639-1</a> and <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO 3166-1 alpha-2</a> 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 <a href="https://www.gnu.org/software/gettext/manual/gettext.html#Rare-Language-Codes">rare languages</a>, three letters are used.</p> <p>For some speakers, the country part may seem redundant. In fact, some languages have dialects in different countries, such as Austrian German (<code class="language-plaintext highlighter-rouge">de_AT</code>) or Brazilian Portuguese (<code class="language-plaintext highlighter-rouge">pt_BR</code>). The second part is used to distinguish between those dialects - when it is not present, it is taken as a “generic” or “hybrid” version of the language.</p> <h3 id="directory-structure">Directory structure</h3> <p>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 will have a folder for each needed locale, and a fixed <code class="language-plaintext highlighter-rouge">LC_MESSAGES</code> folder that will contain all your PO/MO pairs. Example:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="gp"><project root></span><span class="w"> </span><span class="go"> ├─ src/ ├─ templates/ └─ locales/ ├─ forum.pot ├─ site.pot ├─ de/ │ └─ LC_MESSAGES/ │ ├─ forum.mo │ ├─ forum.po │ ├─ site.mo │ └─ site.po ├─ es_ES/ │ └─ LC_MESSAGES/ │ └─ ... ├─ fr/ │ └─ ... ├─ pt_BR/ │ └─ ... └─ pt_PT/ └─ ...</span></code></pre></figure> <h3 id="plural-forms">Plural forms</h3> <p>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 <code class="language-plaintext highlighter-rouge">.po</code> file, you will have to declare the <a href="https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html">plural rules</a> for that language, and translated pieces that are plural-sensitive will have a different form for each of those rules. When 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.</p> <p>Plural rules include the number of plurals available and a boolean test with <code class="language-plaintext highlighter-rouge">n</code> that would define in which rule the given number falls (starting the count with 0). For example:</p> <ul> <li>Japanese: <code class="language-plaintext highlighter-rouge">nplurals=1; plural=0</code> - only one rule</li> <li>English: <code class="language-plaintext highlighter-rouge">nplurals=2; plural=(n != 1);</code> - two rules, first if N is one, second rule otherwise</li> <li>Brazilian Portuguese: <code class="language-plaintext highlighter-rouge">nplurals=2; plural=(n > 1);</code> - two rules, second if N is bigger than one, first otherwise</li> </ul> <p>Now that you understood the basis of how plural rules works - and if you didn’t, please look at a deeper explanation on the <a href="https://lingohub.com/blog/2013/07/php-internationalization-with-gettext-tutorial/#Plurals">LingoHub tutorial</a> -, you might want to copy the ones you need from a <a href="https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html">list</a> instead of writing them by hand.</p> <p>When calling out Gettext to do localization on sentences with counters, you will have to provide it the 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 <code class="language-plaintext highlighter-rouge">.po</code> file a different sentence for each plural rule defined.</p> <h3 id="sample-implementation">Sample implementation</h3> <p>After all that theory, let’s get a little practical. Here’s an excerpt of a <code class="language-plaintext highlighter-rouge">.po</code> file - don’t mind with its format, but with the overall content instead; you will learn how to edit it easily later:</p> <figure class="highlight"><pre><code class="language-po" data-lang="po">msgid "" msgstr "" "Language: pt_BR\n" "Content-Type: text/plain; charset=UTF-8\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" msgid "We are now translating some strings" msgstr "Nós estamos traduzindo algumas strings agora" msgid "Hello %1$s! Your last visit was on %2$s" msgstr "Olá %1$s! Sua última visita foi em %2$s" msgid "Only one unread message" msgid_plural "%d unread messages" msgstr[0] "Só uma mensagem não lida" msgstr[1] "%d mensagens não lidas"</code></pre></figure> <p>The first section works like a header, having the <code class="language-plaintext highlighter-rouge">msgid</code> and <code class="language-plaintext highlighter-rouge">msgstr</code> especially empty. It describes the file encoding, plural forms and other things that are less relevant. The second section translates a simple string from English to Brazilian Portuguese, and the third does the same, but leveraging string replacement from <a href="https://www.php.net/manual/function.sprintf.php"><code class="language-plaintext highlighter-rouge">sprintf</code></a> so the translation may contain the user name and visit date. The last section is a sample of pluralization forms, displaying the singular and plural version as <code class="language-plaintext highlighter-rouge">msgid</code> in English and their corresponding translations as <code class="language-plaintext highlighter-rouge">msgstr</code> 0 and 1 (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 <code class="language-plaintext highlighter-rouge">%d</code>. The plural forms always have two <code class="language-plaintext highlighter-rouge">msgid</code> (singular and plural), so it is advised not to use a complex language as the source of translation.</p> <h3 id="discussion-on-l10n-keys">Discussion on l10n keys</h3> <p>As you might have noticed, we are using as source ID the actual sentence in English. That <code class="language-plaintext highlighter-rouge">msgid</code> is the same used throughout all your <code class="language-plaintext highlighter-rouge">.po</code> files, meaning other languages will have the same format and the same <code class="language-plaintext highlighter-rouge">msgid</code> fields but translated <code class="language-plaintext highlighter-rouge">msgstr</code> lines.</p> <p>Talking about translation keys, there are two main “schools” here:</p> <ol> <li><em><code class="language-plaintext highlighter-rouge">msgid</code> as a real sentence</em>. The main advantages are: <ul> <li>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, you might publish the new page with missing French sentences, and parts of the website would be displayed in English instead;</li> <li>it is much easier for the translator to understand what’s going on and do a proper translation based on the <code class="language-plaintext highlighter-rouge">msgid</code>;</li> <li>it gives you “free” l10n for one language - the source one;</li> <li>The only disadvantage: if you need to change the actual text, you would need to replace the same <code class="language-plaintext highlighter-rouge">msgid</code> across several language files.</li> </ul> </li> <li><em><code class="language-plaintext highlighter-rouge">msgid</code> as a unique, structured key</em>. 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. <ul> <li>it is a great way to have the code organized, separating the text content from the template logic.</li> <li>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 <code class="language-plaintext highlighter-rouge">en.po</code> file, that translators would read to understand what to write in <code class="language-plaintext highlighter-rouge">fr.po</code> for instance.</li> <li>missing translations would display meaningless keys on screen (<code class="language-plaintext highlighter-rouge">top_menu.welcome</code> instead of <code class="language-plaintext highlighter-rouge">Hello there, User!</code> on the said untranslated French page). That is good it as would force translation to be complete before publishing - however, bad as translation issues would be remarkably awful in the interface. Some libraries, though, include an option to specify a given language as “fallback”, having a similar behavior as the other approach.</li> </ul> </li> </ol> <p>The <a href="https://www.gnu.org/software/gettext/manual/gettext.html">Gettext manual</a> favors the first approach as, in general, it is easier for translators and users in case of trouble. That is how we will be working here as well. However, the <a href="https://symfony.com/doc/current/translation.html#using-real-or-keyword-messages">Symfony documentation</a> favors keyword-based translation, to allow for independent changes of all translations without affecting templates as well.</p> <h3 id="everyday-usage">Everyday usage</h3> <p>In a typical application, you would use some Gettext functions while writing static text in your pages. Those sentences would then appear in <code class="language-plaintext highlighter-rouge">.po</code> files, get translated, compiled into <code class="language-plaintext highlighter-rouge">.mo</code> 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:</p> <h4 id="1-a-sample-template-file-including-some-different-gettext-calls">1. A sample template file, including some different gettext calls</h4> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="k">include</span> <span class="s1">'i18n_setup.php'</span> <span class="cp">?></span> <span class="nt"><div</span> <span class="na">id=</span><span class="s">"header"</span><span class="nt">></span> <span class="nt"><h1></span><span class="cp"><?=</span><span class="nb">sprintf</span><span class="p">(</span><span class="nb">gettext</span><span class="p">(</span><span class="s1">'Welcome, %s!'</span><span class="p">),</span> <span class="nv">$name</span><span class="p">)</span><span class="cp">?></span><span class="nt"></h1></span> <span class="c"><!-- code indented this way only for legibility --></span> <span class="cp"><?php</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$unread</span><span class="p">)</span><span class="o">:</span> <span class="cp">?></span> <span class="nt"><h2></span><span class="cp"><?=</span><span class="nb">sprintf</span><span class="p">(</span> <span class="nb">ngettext</span><span class="p">(</span><span class="s1">'Only one unread message'</span><span class="p">,</span> <span class="s1">'%d unread messages'</span><span class="p">,</span> <span class="nv">$unread</span><span class="p">),</span> <span class="nv">$unread</span><span class="p">)</span><span class="cp">?></span> <span class="nt"></h2></span> <span class="cp"><?php</span> <span class="k">endif</span> <span class="cp">?></span> <span class="nt"></div></span> <span class="nt"><h1></span><span class="cp"><?=</span><span class="nb">gettext</span><span class="p">(</span><span class="s1">'Introduction'</span><span class="p">)</span><span class="cp">?></span><span class="nt"></h1></span> <span class="nt"><p></span><span class="cp"><?=</span><span class="nb">gettext</span><span class="p">(</span><span class="s1">'We\'re now translating some strings'</span><span class="p">)</span><span class="cp">?></span><span class="nt"></p></span></code></pre></figure> <ul> <li><a href="https://www.php.net/manual/function.gettext.php"><code class="language-plaintext highlighter-rouge">gettext()</code></a> simply translates a <code class="language-plaintext highlighter-rouge">msgid</code> into its corresponding <code class="language-plaintext highlighter-rouge">msgstr</code> for a given language. There’s also the shorthand function <code class="language-plaintext highlighter-rouge">_()</code> that works the same way;</li> <li><a href="https://www.php.net/manual/function.ngettext.php"><code class="language-plaintext highlighter-rouge">ngettext()</code></a> does the same but with plural rules;</li> <li>There are also <a href="https://www.php.net/manual/function.dgettext.php"><code class="language-plaintext highlighter-rouge">dgettext()</code></a> and <a href="https://www.php.net/manual/function.dngettext.php"><code class="language-plaintext highlighter-rouge">dngettext()</code></a>, that allow you to override the domain for a single call. More on domain configuration in the next example.</li> </ul> <h4 id="2-a-sample-setup-file-i18n_setupphp-as-used-above-selecting-the-correct-locale-and-configuring-gettext">2. A sample setup file (<code class="language-plaintext highlighter-rouge">i18n_setup.php</code> as used above), selecting the correct locale and configuring Gettext</h4> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="cd">/** * Verifies if the given $locale is supported in the project * @param string $locale * @return bool */</span> <span class="k">function</span> <span class="n">valid</span><span class="p">(</span><span class="nv">$locale</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nb">in_array</span><span class="p">(</span><span class="nv">$locale</span><span class="p">,</span> <span class="p">[</span><span class="s1">'en_US'</span><span class="p">,</span> <span class="s1">'en'</span><span class="p">,</span> <span class="s1">'pt_BR'</span><span class="p">,</span> <span class="s1">'pt'</span><span class="p">,</span> <span class="s1">'es_ES'</span><span class="p">,</span> <span class="s1">'es'</span><span class="p">]);</span> <span class="p">}</span> <span class="c1">//setting the source/default locale, for informational purposes</span> <span class="nv">$lang</span> <span class="o">=</span> <span class="s1">'en_US'</span><span class="p">;</span> <span class="k">if</span> <span class="p">(</span><span class="k">isset</span><span class="p">(</span><span class="nv">$_GET</span><span class="p">[</span><span class="s1">'lang'</span><span class="p">])</span> <span class="o">&&</span> <span class="nf">valid</span><span class="p">(</span><span class="nv">$_GET</span><span class="p">[</span><span class="s1">'lang'</span><span class="p">]))</span> <span class="p">{</span> <span class="c1">// the locale can be changed through the query-string</span> <span class="nv">$lang</span> <span class="o">=</span> <span class="nv">$_GET</span><span class="p">[</span><span class="s1">'lang'</span><span class="p">];</span> <span class="c1">//you should sanitize this!</span> <span class="nb">setcookie</span><span class="p">(</span><span class="s1">'lang'</span><span class="p">,</span> <span class="nv">$lang</span><span class="p">);</span> <span class="c1">//it's stored in a cookie so it can be reused</span> <span class="p">}</span> <span class="k">elseif</span> <span class="p">(</span><span class="k">isset</span><span class="p">(</span><span class="nv">$_COOKIE</span><span class="p">[</span><span class="s1">'lang'</span><span class="p">])</span> <span class="o">&&</span> <span class="nf">valid</span><span class="p">(</span><span class="nv">$_COOKIE</span><span class="p">[</span><span class="s1">'lang'</span><span class="p">]))</span> <span class="p">{</span> <span class="c1">// if the cookie is present instead, let's just keep it</span> <span class="nv">$lang</span> <span class="o">=</span> <span class="nv">$_COOKIE</span><span class="p">[</span><span class="s1">'lang'</span><span class="p">];</span> <span class="c1">//you should sanitize this!</span> <span class="p">}</span> <span class="k">elseif</span> <span class="p">(</span><span class="k">isset</span><span class="p">(</span><span class="nv">$_SERVER</span><span class="p">[</span><span class="s1">'HTTP_ACCEPT_LANGUAGE'</span><span class="p">]))</span> <span class="p">{</span> <span class="c1">// default: look for the languages the browser says the user accepts</span> <span class="nv">$langs</span> <span class="o">=</span> <span class="nb">explode</span><span class="p">(</span><span class="s1">','</span><span class="p">,</span> <span class="nv">$_SERVER</span><span class="p">[</span><span class="s1">'HTTP_ACCEPT_LANGUAGE'</span><span class="p">]);</span> <span class="nb">array_walk</span><span class="p">(</span><span class="nv">$langs</span><span class="p">,</span> <span class="k">function</span> <span class="p">(</span><span class="o">&</span><span class="nv">$lang</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$lang</span> <span class="o">=</span> <span class="nb">strtr</span><span class="p">(</span><span class="nb">strtok</span><span class="p">(</span><span class="nv">$lang</span><span class="p">,</span> <span class="s1">';'</span><span class="p">),</span> <span class="p">[</span><span class="s1">'-'</span> <span class="o">=></span> <span class="s1">'_'</span><span class="p">]);</span> <span class="p">});</span> <span class="k">foreach</span> <span class="p">(</span><span class="nv">$langs</span> <span class="k">as</span> <span class="nv">$browser_lang</span><span class="p">)</span> <span class="p">{</span> <span class="k">if</span> <span class="p">(</span><span class="nf">valid</span><span class="p">(</span><span class="nv">$browser_lang</span><span class="p">))</span> <span class="p">{</span> <span class="nv">$lang</span> <span class="o">=</span> <span class="nv">$browser_lang</span><span class="p">;</span> <span class="k">break</span><span class="p">;</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> <span class="c1">// here we define the global system locale given the found language</span> <span class="nb">putenv</span><span class="p">(</span><span class="s2">"LANG=</span><span class="nv">$lang</span><span class="s2">"</span><span class="p">);</span> <span class="c1">// this might be useful for date functions (LC_TIME) or money formatting (LC_MONETARY), for instance</span> <span class="nb">setlocale</span><span class="p">(</span><span class="no">LC_ALL</span><span class="p">,</span> <span class="nv">$lang</span><span class="p">);</span> <span class="c1">// this will make Gettext look for ../locales/<lang>/LC_MESSAGES/main.mo</span> <span class="nb">bindtextdomain</span><span class="p">(</span><span class="s1">'main'</span><span class="p">,</span> <span class="s1">'../locales'</span><span class="p">);</span> <span class="c1">// indicates in what encoding the file should be read</span> <span class="nb">bind_textdomain_codeset</span><span class="p">(</span><span class="s1">'main'</span><span class="p">,</span> <span class="s1">'UTF-8'</span><span class="p">);</span> <span class="c1">// if your application has additional domains, as cited before, you should bind them here as well</span> <span class="nb">bindtextdomain</span><span class="p">(</span><span class="s1">'forum'</span><span class="p">,</span> <span class="s1">'../locales'</span><span class="p">);</span> <span class="nb">bind_textdomain_codeset</span><span class="p">(</span><span class="s1">'forum'</span><span class="p">,</span> <span class="s1">'UTF-8'</span><span class="p">);</span> <span class="c1">// here we indicate the default domain the gettext() calls will respond to</span> <span class="nb">textdomain</span><span class="p">(</span><span class="s1">'main'</span><span class="p">);</span> <span class="c1">// this would look for the string in forum.mo instead of main.mo</span> <span class="c1">// echo dgettext('forum', 'Welcome back!');</span> <span class="cp">?></span></code></pre></figure> <h4 id="3-preparing-translation-for-the-first-run">3. Preparing translation for the first run</h4> <p>One of the great advantages Gettext has over custom framework i18n packages is its extensive and powerful file format. “Oh man, that’s quite hard to understand and edit by hand, a simple array would be easier!” Make no mistake, applications like <a href="https://poedit.net">Poedit</a> are here to help - <em>a lot</em>. You can get the program from <a href="https://poedit.net/download">their website</a>, it’s free and available for all platforms. It’s a pretty easy tool to get used to, and a very powerful one at the same time - using all features Gettext has available. This guide is based on PoEdit 1.8.</p> <p>In the first run, you should select “File > New…” from the menu. You’ll be asked straight ahead for the language: here you can select/filter the language you want to translate to, or use that format we mentioned before, such as <code class="language-plaintext highlighter-rouge">en_US</code> or <code class="language-plaintext highlighter-rouge">pt_BR</code>.</p> <p>Now, save the file - using that directory structure we mentioned as well. Then you should click “Extract from sources”, and here you’ll configure various settings for the extraction and translation tasks. You’ll be able to find all those later through “Catalog > Properties”:</p> <ul> <li>Source paths: here you must include all folders from the project where <code class="language-plaintext highlighter-rouge">gettext()</code> (and siblings) are called - this is usually your templates/views folder(s). This is the only mandatory setting;</li> <li>Translation properties: <ul> <li>Project name and version, Team and Team’s email address: useful information that goes in the .po file header;</li> <li>Plural forms: here go those rules we mentioned before - there’s 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.</li> <li>Charsets: UTF-8, preferably;</li> <li>Source code charset: set here the charset used by your codebase - probably UTF-8 as well, right?</li> </ul> </li> <li>Source keywords: The underlying software knows how <code class="language-plaintext highlighter-rouge">gettext()</code> and similar function calls look like in several programming languages, but you might as well create your own translation functions. It will be here you’ll add those other methods. This will be discussed later in the “Tips” section.</li> </ul> <p>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 you’ll 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.</p> <h4 id="4-translating-strings">4. Translating strings</h4> <p>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 cannot be modified as 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 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 the different final forms.</p> <p>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 translations, based on other ones you did. Those guesses and the changed entries will receive a “Fuzzy” marker, 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 are not sure about: just mark Fuzzy, and someone else will review later.</p> <p>Finally, it is advised to leave “View > Untranslated entries first” marked, as it will help you <em>a lot</em> to not forget any entry. From that menu, you can also open parts of the UI that allow you to leave contextual information for translators if needed.</p> <h3 id="tips--tricks">Tips & Tricks</h3> <h4 id="possible-caching-issues">Possible caching issues</h4> <p>If you are running PHP as a module on Apache (<code class="language-plaintext highlighter-rouge">mod_php</code>), you might face issues with the <code class="language-plaintext highlighter-rouge">.mo</code> file being cached. 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.</p> <h4 id="additional-helper-functions">Additional helper functions</h4> <p>As preferred by many people, it is easier to use <code class="language-plaintext highlighter-rouge">_()</code> instead of <code class="language-plaintext highlighter-rouge">gettext()</code>. Many custom i18n libraries from frameworks use something similar to <code class="language-plaintext highlighter-rouge">t()</code> 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 <code class="language-plaintext highlighter-rouge">__()</code> or <code class="language-plaintext highlighter-rouge">_n()</code> for <code class="language-plaintext highlighter-rouge">ngettext()</code>, or maybe a fancy <code class="language-plaintext highlighter-rouge">_r()</code> that would join <code class="language-plaintext highlighter-rouge">gettext()</code> and <code class="language-plaintext highlighter-rouge">sprintf()</code> calls. Other libraries, such as <a href="https://github.com/php-gettext/Gettext">php-gettext’s Gettext</a> also provide helper functions like these.</p> <p>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 is very easy. It is just a field in the <code class="language-plaintext highlighter-rouge">.po</code> file, or a Settings screen on Poedit. In the editor, that option is inside “Catalog > Properties > Source keywords”. Remember: Gettext already knows the default functions for many languages, so don’t be afraid if that list seems empty. You need to include there the specifications of those new functions, following <a href="https://www.gnu.org/software/gettext/manual/gettext.html#Language-specific-options">a specific format</a>:</p> <ul> <li>if you create something like <code class="language-plaintext highlighter-rouge">t()</code> that simply returns the translation for a string, you can specify it as <code class="language-plaintext highlighter-rouge">t</code>. Gettext will know the only function argument is the string to be translated;</li> <li>if the function has more than one argument, you can specify in which one the first string is - and if needed, the plural form as well. For instance, if we call our function like this: <code class="language-plaintext highlighter-rouge">__('one user', '%d users', $number)</code>, the specification would be <code class="language-plaintext highlighter-rouge">__:1,2</code>, meaning the first form is the first argument, and the second form is the second argument. If your number comes as the first argument instead, the spec would be <code class="language-plaintext highlighter-rouge">__:2,3</code>, indicating the first form is the second argument, and so on.</li> </ul> <p>After including those new rules in the <code class="language-plaintext highlighter-rouge">.po</code> file, a new scan will bring in your new strings just as easy as before.</p> <h3 id="references">References</h3> <ul> <li><a href="https://en.wikipedia.org/wiki/Internationalization_and_localization">Wikipedia: i18n and l10n</a></li> <li><a href="https://en.wikipedia.org/wiki/Gettext">Wikipedia: Gettext</a></li> <li><a href="https://lingohub.com/blog/2013/07/php-internationalization-with-gettext-tutorial/">LingoHub: PHP internationalization with gettext tutorial</a></li> <li><a href="https://www.php.net/manual/book.gettext.php">PHP Manual: Gettext</a></li> <li><a href="https://www.gnu.org/software/gettext/manual/gettext.html">Gettext Manual</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="dependency_injection"> <h1 id="dependency_injection_title">Dependency Injection</h1> <p>From <a href="https://wikipedia.org/wiki/Dependency_injection">Wikipedia</a>:</p> <blockquote> <p>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.</p> </blockquote> <p>This quote makes the concept sound much more complicated than it actually is. Dependency Injection is providing a component with its dependencies either through constructor injection, method calls or the setting of properties. It is that simple.</p> </section> <section class="chapter" id="basic_concept"> <h2 id="basic_concept_title">Basic Concept</h2> <p>We can demonstrate the concept with a simple, yet naive example.</p> <p>Here we have a <code class="language-plaintext highlighter-rouge">Database</code> class that requires an adapter to speak to the database. We instantiate the adapter in the constructor and create a hard dependency. This makes testing difficult and means the <code class="language-plaintext highlighter-rouge">Database</code> class is very tightly coupled to the adapter.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="kn">namespace</span> <span class="nn">Database</span><span class="p">;</span> <span class="kd">class</span> <span class="nc">Database</span> <span class="p">{</span> <span class="k">protected</span> <span class="nv">$adapter</span><span class="p">;</span> <span class="k">public</span> <span class="k">function</span> <span class="n">__construct</span><span class="p">()</span> <span class="p">{</span> <span class="nv">$this</span><span class="o">-></span><span class="n">adapter</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">MySqlAdapter</span><span class="p">;</span> <span class="p">}</span> <span class="p">}</span> <span class="kd">class</span> <span class="nc">MysqlAdapter</span> <span class="p">{}</span></code></pre></figure> <p>This code can be refactored to use Dependency Injection and therefore loosen the dependency. Here, we inject the dependency in a constructor and use the <a href="https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.constructor.promotion">constructor property promotion</a> so it is available as a property across the class:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="kn">namespace</span> <span class="nn">Database</span><span class="p">;</span> <span class="kd">class</span> <span class="nc">Database</span> <span class="p">{</span> <span class="k">public</span> <span class="k">function</span> <span class="n">__construct</span><span class="p">(</span><span class="k">protected</span> <span class="kt">MySqlAdapter</span> <span class="nv">$adapter</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span> <span class="p">}</span> <span class="kd">class</span> <span class="nc">MysqlAdapter</span> <span class="p">{}</span></code></pre></figure> <p>Now we are giving the <code class="language-plaintext highlighter-rouge">Database</code> 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 <code class="language-plaintext highlighter-rouge">$adapter</code> property was <code class="language-plaintext highlighter-rouge">public</code> we could set it directly.</p> </section> <section class="chapter" id="complex_problem"> <h2 id="complex_problem_title">Complex Problem</h2> <p>If you have ever read about Dependency Injection then you have probably seen the terms <em>“Inversion of Control”</em> or <em>“Dependency Inversion Principle”</em>. These are the complex problems that Dependency Injection solves.</p> <h3 id="inversion-of-control">Inversion of Control</h3> <p>Inversion of Control is as it says, “inverting the control” of a system by keeping organizational control entirely separate from our objects. In terms of Dependency Injection, this means loosening our dependencies by controlling and instantiating them elsewhere in the system.</p> <p>For years, PHP frameworks have been achieving Inversion of Control, however, the question became, which part of control 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 <strong>is</strong> Inversion of Control, however, instead of loosening dependencies, this method simply moved them.</p> <p>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.</p> <h3 id="solid">S.O.L.I.D.</h3> <h4 id="single-responsibility-principle">Single Responsibility Principle</h4> <p>The Single Responsibility Principle is about actors and high-level architecture. It states that “A class should have only one reason to change.” This means that every class should <em>only</em> 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 <em>reusability</em>. By designing our class to do just one thing, we can use (or re-use) it in any other program without changing it.</p> <h4 id="openclosed-principle">Open/Closed Principle</h4> <p>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 <em>interfaces</em>, then type-hint against those interfaces instead of specific classes.</p> <p>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.</p> <h4 id="liskov-substitution-principle">Liskov Substitution Principle</h4> <p>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. Martin’s words, “Subtypes must be substitutable for their base types.”</p> <p>For example, if we have a <code class="language-plaintext highlighter-rouge">FileInterface</code> interface which defines an <code class="language-plaintext highlighter-rouge">embed()</code> method, and we have <code class="language-plaintext highlighter-rouge">Audio</code> and <code class="language-plaintext highlighter-rouge">Video</code> classes which both implement the <code class="language-plaintext highlighter-rouge">FileInterface</code> interface, then we can expect that the usage of the <code class="language-plaintext highlighter-rouge">embed()</code> method will always do the thing that we intend. If we later create a <code class="language-plaintext highlighter-rouge">PDF</code> class or a <code class="language-plaintext highlighter-rouge">Gist</code> class which implement the <code class="language-plaintext highlighter-rouge">FileInterface</code> interface, we will already know and understand what the <code class="language-plaintext highlighter-rouge">embed()</code> 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., <code class="language-plaintext highlighter-rouge">FileInterface</code>) to another we don’t need to change anything else in our program.</p> <h4 id="interface-segregation-principle">Interface Segregation Principle</h4> <p>The Interface Segregation Principle (ISP) is about <em>business-logic-to-clients</em> 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.</p> <p>For example, a <code class="language-plaintext highlighter-rouge">Car</code> or <code class="language-plaintext highlighter-rouge">Bus</code> class would be interested in a <code class="language-plaintext highlighter-rouge">steeringWheel()</code> method, but a <code class="language-plaintext highlighter-rouge">Motorcycle</code> or <code class="language-plaintext highlighter-rouge">Tricycle</code> class would not. Conversely, a <code class="language-plaintext highlighter-rouge">Motorcycle</code> or <code class="language-plaintext highlighter-rouge">Tricycle</code> class would be interested in a <code class="language-plaintext highlighter-rouge">handlebars()</code> method, but a <code class="language-plaintext highlighter-rouge">Car</code> or <code class="language-plaintext highlighter-rouge">Bus</code> class would not. There is no need to have all of these types of vehicles implement support for both <code class="language-plaintext highlighter-rouge">steeringWheel()</code> as well as <code class="language-plaintext highlighter-rouge">handlebars()</code>, so we should break-apart the source interface.</p> <h4 id="dependency-inversion-principle">Dependency Inversion Principle</h4> <p>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 <em>“Depend on Abstractions. Do not depend on concretions.”</em>. 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.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="kn">namespace</span> <span class="nn">Database</span><span class="p">;</span> <span class="kd">class</span> <span class="nc">Database</span> <span class="p">{</span> <span class="k">public</span> <span class="k">function</span> <span class="n">__construct</span><span class="p">(</span><span class="k">protected</span> <span class="kt">AdapterInterface</span> <span class="nv">$adapter</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span> <span class="p">}</span> <span class="kd">interface</span> <span class="nc">AdapterInterface</span> <span class="p">{}</span> <span class="kd">class</span> <span class="nc">MysqlAdapter</span> <span class="kd">implements</span> <span class="nc">AdapterInterface</span> <span class="p">{}</span></code></pre></figure> <p>There are several benefits to the <code class="language-plaintext highlighter-rouge">Database</code> class now depending on an interface rather than a concretion.</p> <p>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 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.</p> <p>An even bigger benefit to this method is that our code is now much more scalable. If a year down the line we decide that we want to migrate to a different type of database, we can write an adapter that implements the original interface and injects that instead, no more refactoring would be required as we can ensure that the adapter follows the contract set by the interface.</p> </section> <section class="chapter" id="containers"> <h2 id="containers_title">Containers</h2> <p>The first thing you should understand about Dependency Injection Containers is that they are not the same thing as Dependency Injection. A container is a convenience utility that helps us implement Dependency Injection, however, they can be and often are misused to implement an anti-pattern, Service Location. Injecting a DI container as a Service Locator in to your classes arguably creates a harder dependency on the container than the dependency you are replacing. It also makes your code much less transparent and ultimately harder to test.</p> <p>Most modern frameworks have their own Dependency Injection Container that allows you to wire your dependencies together through configuration. What this means in practice is that you can write application code that is as clean and de-coupled as the framework it is built on.</p> </section> <section class="chapter" id="further_reading"> <h2 id="further_reading_title">Further Reading</h2> <ul> <li><a href="http://fabien.potencier.org/what-is-dependency-injection.html">What is Dependency Injection?</a></li> <li><a href="https://mwop.net/blog/260-Dependency-Injection-An-analogy.html">Dependency Injection: An analogy</a></li> <li><a href="https://code.tutsplus.com/tutorials/dependency-injection-huh--net-26903">Dependency Injection: Huh?</a></li> <li><a href="https://medium.com/philipobenito/dependency-injection-as-a-tool-for-testing-902c21c147f1">Dependency Injection as a tool for testing</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="databases"> <h1 id="databases_title">Databases</h1> <p>Many times your PHP code will use a database to persist information. You have a few options to connect and interact with your database. The recommended option <strong>until PHP 5.1.0</strong> was to use native drivers such as <a href="https://www.php.net/mysqli">mysqli</a>, <a href="https://www.php.net/pgsql">pgsql</a>, <a href="https://www.php.net/mssql">mssql</a>, etc.</p> <p>Native drivers are great if you are only using <em>one</em> database in your application, but if, for example, you are using MySQL and a little bit of MSSQL, or you need to connect to an Oracle database, then you will not be able to use the same drivers. You’ll need to learn a brand new API for each database — and that can get silly.</p> </section> <section class="chapter" id="mysql_extension"> <h2 id="mysql_extension_title">MySQL Extension</h2> <p>The <a href="https://www.php.net/mysqli">mysql</a> extension for PHP is incredibly old and has been superseded by two other extensions:</p> <ul> <li><a href="https://www.php.net/mysqli">mysqli</a></li> <li><a href="https://www.php.net/pdo">pdo</a></li> </ul> <p>Not only did development stop long ago on <a href="https://www.php.net/mysqli">mysql</a>, but it <strong>has been <a href="https://www.php.net/manual/migration70.removed-exts-sapis.php">officially removed in PHP 7.0</a></strong>.</p> <p>To save digging into your <code class="language-plaintext highlighter-rouge">php.ini</code> settings to see which module you are using, one option is to search for <code class="language-plaintext highlighter-rouge">mysql_*</code> in your editor of choice. If any functions such as <code class="language-plaintext highlighter-rouge">mysql_connect()</code> and <code class="language-plaintext highlighter-rouge">mysql_query()</code> show up, then <code class="language-plaintext highlighter-rouge">mysql</code> is in use.</p> <p>Even if you are not using PHP 7.x or later yet, failing to consider this upgrade as soon as possible will lead to greater hardship when the PHP upgrade does come about. The best option is to replace mysql usage with <a href="https://www.php.net/mysqli">mysqli</a> or <a href="https://www.php.net/pdo">PDO</a> in your applications within your own development schedules so you won’t be rushed later on.</p> <p><strong>If you are upgrading from <a href="https://www.php.net/mysqli">mysql</a> to <a href="https://www.php.net/mysqli">mysqli</a>, beware lazy upgrade guides that suggest you can simply find and replace <code class="language-plaintext highlighter-rouge">mysql_*</code> with <code class="language-plaintext highlighter-rouge">mysqli_*</code>. 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 <a href="https://www.php.net/pdo">PDO</a>.</strong></p> <ul> <li><a href="https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection">MySQLi Prepared Statements</a></li> <li><a href="https://www.php.net/mysqlinfo.api.choosing">PHP: Choosing an API for MySQL</a></li> </ul> </section> <section class="chapter" id="pdo_extension"> <h2 id="pdo_extension_title">PDO Extension</h2> <p><a href="https://www.php.net/pdo">PDO</a> is a database connection abstraction library — built into PHP since 5.1.0 — that provides a common interface to talk with many different databases. For example, you can use basically identical code to interface with MySQL or SQLite:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="c1">// PDO + MySQL</span> <span class="nv">$pdo</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">PDO</span><span class="p">(</span><span class="s1">'mysql:host=example.com;dbname=database'</span><span class="p">,</span> <span class="s1">'user'</span><span class="p">,</span> <span class="s1">'password'</span><span class="p">);</span> <span class="nv">$statement</span> <span class="o">=</span> <span class="nv">$pdo</span><span class="o">-></span><span class="nf">query</span><span class="p">(</span><span class="s2">"SELECT some_field FROM some_table"</span><span class="p">);</span> <span class="nv">$row</span> <span class="o">=</span> <span class="nv">$statement</span><span class="o">-></span><span class="nf">fetch</span><span class="p">(</span><span class="no">PDO</span><span class="o">::</span><span class="no">FETCH_ASSOC</span><span class="p">);</span> <span class="k">echo</span> <span class="nb">htmlentities</span><span class="p">(</span><span class="nv">$row</span><span class="p">[</span><span class="s1">'some_field'</span><span class="p">]);</span> <span class="c1">// PDO + SQLite</span> <span class="nv">$pdo</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">PDO</span><span class="p">(</span><span class="s1">'sqlite:/path/db/foo.sqlite'</span><span class="p">);</span> <span class="nv">$statement</span> <span class="o">=</span> <span class="nv">$pdo</span><span class="o">-></span><span class="nf">query</span><span class="p">(</span><span class="s2">"SELECT some_field FROM some_table"</span><span class="p">);</span> <span class="nv">$row</span> <span class="o">=</span> <span class="nv">$statement</span><span class="o">-></span><span class="nf">fetch</span><span class="p">(</span><span class="no">PDO</span><span class="o">::</span><span class="no">FETCH_ASSOC</span><span class="p">);</span> <span class="k">echo</span> <span class="nb">htmlentities</span><span class="p">(</span><span class="nv">$row</span><span class="p">[</span><span class="s1">'some_field'</span><span class="p">]);</span></code></pre></figure> <p>PDO will not translate your SQL queries or emulate missing features; it is purely for connecting to multiple types of database with the same API.</p> <p>More importantly, <code class="language-plaintext highlighter-rouge">PDO</code> allows you to safely inject foreign input (e.g. IDs) into your SQL queries without worrying about database SQL injection attacks. This is possible using PDO statements and bound parameters.</p> <p>Let’s assume a PHP script receives a numeric ID as a query parameter. This ID should be used to fetch a user record from a database. This is the <code class="language-plaintext highlighter-rouge">wrong</code> way to do this:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="nv">$pdo</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">PDO</span><span class="p">(</span><span class="s1">'sqlite:/path/db/users.db'</span><span class="p">);</span> <span class="nv">$pdo</span><span class="o">-></span><span class="nf">query</span><span class="p">(</span><span class="s2">"SELECT name FROM users WHERE id = "</span> <span class="mf">.</span> <span class="nv">$_GET</span><span class="p">[</span><span class="s1">'id'</span><span class="p">]);</span> <span class="c1">// <-- NO!</span></code></pre></figure> <p>This is terrible code. You are inserting a raw query parameter into a SQL query. This will get you hacked in a heartbeat, using a practice called <a href="https://web.archive.org/web/20210413233627/http://wiki.hashphp.org/Validation">SQL Injection</a>. Just imagine if a hacker passes in an inventive <code class="language-plaintext highlighter-rouge">id</code> parameter by calling a URL like <code class="language-plaintext highlighter-rouge">http://domain.com/?id=1%3BDELETE+FROM+users</code>. This will set the <code class="language-plaintext highlighter-rouge">$_GET['id']</code> variable to <code class="language-plaintext highlighter-rouge">1;DELETE FROM users</code> which will delete all of your users! Instead, you should sanitize the ID input using PDO bound parameters.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="nv">$pdo</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">PDO</span><span class="p">(</span><span class="s1">'sqlite:/path/db/users.db'</span><span class="p">);</span> <span class="nv">$stmt</span> <span class="o">=</span> <span class="nv">$pdo</span><span class="o">-></span><span class="nf">prepare</span><span class="p">(</span><span class="s1">'SELECT name FROM users WHERE id = :id'</span><span class="p">);</span> <span class="nv">$id</span> <span class="o">=</span> <span class="nb">filter_input</span><span class="p">(</span><span class="no">INPUT_GET</span><span class="p">,</span> <span class="s1">'id'</span><span class="p">,</span> <span class="no">FILTER_SANITIZE_NUMBER_INT</span><span class="p">);</span> <span class="c1">// <-- filter your data first (see [Data Filtering](#data_filtering)), especially important for INSERT, UPDATE, etc.</span> <span class="nv">$stmt</span><span class="o">-></span><span class="nf">bindParam</span><span class="p">(</span><span class="s1">':id'</span><span class="p">,</span> <span class="nv">$id</span><span class="p">,</span> <span class="no">PDO</span><span class="o">::</span><span class="no">PARAM_INT</span><span class="p">);</span> <span class="c1">// <-- Automatically sanitized for SQL by PDO</span> <span class="nv">$stmt</span><span class="o">-></span><span class="nf">execute</span><span class="p">();</span></code></pre></figure> <p>This is correct code. It uses a bound parameter on a PDO statement. This escapes the foreign input ID before it is introduced to the database preventing potential SQL injection attacks.</p> <p>For writes, such as INSERT or UPDATE, it’s especially critical to still <a href="#data_filtering">filter your data</a> first and sanitize it for other things (removal of HTML tags, JavaScript, etc). PDO will only sanitize it for SQL, not for your application.</p> <ul> <li><a href="https://www.php.net/pdo">Learn about PDO</a></li> </ul> <p>You should also be aware that database connections use up resources and it was not unheard-of to have resources exhausted if connections were not implicitly closed, however this was more common in other languages. Using PDO you can implicitly close the connection by destroying the object by ensuring all remaining references to it are deleted, i.e. set to NULL. If you don’t do this explicitly, PHP will automatically close the connection when your script ends - unless of course you are using persistent connections.</p> <ul> <li><a href="https://www.php.net/pdo.connections">Learn about PDO connections</a></li> </ul> </section> <section class="chapter" id="databases_interacting"> <h2 id="databases_interacting_title">Interacting with Databases</h2> <p>When developers first start to learn PHP, they often end up mixing their database interaction up with their presentation logic, using code that might look like this:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="nt"><ul></span> <span class="cp"><?php</span> <span class="k">foreach</span> <span class="p">(</span><span class="nv">$db</span><span class="o">-></span><span class="nf">query</span><span class="p">(</span><span class="s1">'SELECT * FROM table'</span><span class="p">)</span> <span class="k">as</span> <span class="nv">$row</span><span class="p">)</span> <span class="p">{</span> <span class="k">echo</span> <span class="s2">"<li>"</span><span class="mf">.</span><span class="nv">$row</span><span class="p">[</span><span class="s1">'field1'</span><span class="p">]</span><span class="mf">.</span><span class="s2">" - "</span><span class="mf">.</span><span class="nv">$row</span><span class="p">[</span><span class="s1">'field1'</span><span class="p">]</span><span class="mf">.</span><span class="s2">"</li>"</span><span class="p">;</span> <span class="p">}</span> <span class="cp">?></span> <span class="nt"></ul></span></code></pre></figure> <p>This is bad practice for all sorts of reasons, mainly that it’s hard to debug, hard to test, hard to read and it is going to output a lot of fields if you don’t put a limit on there.</p> <p>While there are many other solutions to doing this - depending on if you prefer <a href="/#object-oriented-programming">OOP</a> or <a href="/#functional-programming">functional programming</a> - there must be some element of separation.</p> <p>Consider the most basic step:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="k">function</span> <span class="n">getAllFoos</span><span class="p">(</span><span class="nv">$db</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nv">$db</span><span class="o">-></span><span class="nf">query</span><span class="p">(</span><span class="s1">'SELECT * FROM table'</span><span class="p">);</span> <span class="p">}</span> <span class="nv">$results</span> <span class="o">=</span> <span class="nf">getAllFoos</span><span class="p">(</span><span class="nv">$db</span><span class="p">);</span> <span class="k">foreach</span> <span class="p">(</span><span class="nv">$results</span> <span class="k">as</span> <span class="nv">$row</span><span class="p">)</span> <span class="p">{</span> <span class="k">echo</span> <span class="s2">"<li>"</span><span class="mf">.</span><span class="nv">$row</span><span class="p">[</span><span class="s1">'field1'</span><span class="p">]</span><span class="mf">.</span><span class="s2">" - "</span><span class="mf">.</span><span class="nv">$row</span><span class="p">[</span><span class="s1">'field1'</span><span class="p">]</span><span class="mf">.</span><span class="s2">"</li>"</span><span class="p">;</span> <span class="c1">// BAD!!</span> <span class="p">}</span></code></pre></figure> <p>That is a good start. Put those two items in two different files and you’ve got some clean separation.</p> <p>Create a class to place that method in and you have a “Model”. Create a simple <code class="language-plaintext highlighter-rouge">.php</code> file to put the presentation logic in and you have a “View”, which is very nearly <a href="https://code.tutsplus.com/tutorials/mvc-for-noobs--net-10488">MVC</a> - a common OOP architecture for most <a href="/#frameworks">frameworks</a>.</p> <p><strong>foo.php</strong></p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="nv">$db</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">PDO</span><span class="p">(</span><span class="s1">'mysql:host=localhost;dbname=testdb;charset=utf8mb4'</span><span class="p">,</span> <span class="s1">'username'</span><span class="p">,</span> <span class="s1">'password'</span><span class="p">);</span> <span class="c1">// Make your model available</span> <span class="k">include</span> <span class="s1">'models/FooModel.php'</span><span class="p">;</span> <span class="c1">// Create an instance</span> <span class="nv">$fooModel</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">FooModel</span><span class="p">(</span><span class="nv">$db</span><span class="p">);</span> <span class="c1">// Get the list of Foos</span> <span class="nv">$fooList</span> <span class="o">=</span> <span class="nv">$fooModel</span><span class="o">-></span><span class="nf">getAllFoos</span><span class="p">();</span> <span class="c1">// Show the view</span> <span class="k">include</span> <span class="s1">'views/foo-list.php'</span><span class="p">;</span></code></pre></figure> <p><strong>models/FooModel.php</strong></p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="kd">class</span> <span class="nc">FooModel</span> <span class="p">{</span> <span class="k">public</span> <span class="k">function</span> <span class="n">__construct</span><span class="p">(</span><span class="k">protected</span> <span class="kt">PDO</span> <span class="nv">$db</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span> <span class="k">public</span> <span class="k">function</span> <span class="n">getAllFoos</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="nv">$this</span><span class="o">-></span><span class="n">db</span><span class="o">-></span><span class="nf">query</span><span class="p">(</span><span class="s1">'SELECT * FROM table'</span><span class="p">);</span> <span class="p">}</span> <span class="p">}</span></code></pre></figure> <p><strong>views/foo-list.php</strong></p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="k">foreach</span> <span class="p">(</span><span class="nv">$fooList</span> <span class="k">as</span> <span class="nv">$row</span><span class="p">)</span><span class="o">:</span> <span class="cp">?></span> <span class="nt"><li></span><span class="cp"><?=</span> <span class="nv">$row</span><span class="p">[</span><span class="s1">'field1'</span><span class="p">]</span> <span class="cp">?></span> - <span class="cp"><?=</span> <span class="nv">$row</span><span class="p">[</span><span class="s1">'field1'</span><span class="p">]</span> <span class="cp">?></span><span class="nt"></li></span> <span class="cp"><?php</span> <span class="k">endforeach</span> <span class="cp">?></span></code></pre></figure> <p>This is essentially the same as what most modern frameworks are doing, albeit a little more manual. You might not need to do all of that every time, but mixing together too much presentation logic and database interaction can be a real problem if you ever want to <a href="/#unit-testing">unit-test</a> your application.</p> </section> <section class="chapter" id="databases_abstraction_layers"> <h2 id="databases_abstraction_layers_title">Abstraction Layers</h2> <p>Many frameworks provide their own abstraction layer which may or may not sit on top of <a href="https://www.php.net/book.pdo">PDO</a>. These will often emulate features for one database system that is missing from another by wrapping your queries in PHP methods, giving you actual database abstraction instead of just the connection abstraction that PDO provides. This will of course add a little overhead, but if you are building a portable application that needs to work with MySQL, PostgreSQL and SQLite then a little overhead will be worth it for the sake of code cleanliness.</p> <p>Some abstraction layers have been built using the <a href="https://www.php-fig.org/psr/psr-0/">PSR-0</a> or <a href="https://www.php-fig.org/psr/psr-4/">PSR-4</a> namespace standards so can be installed in any application you like:</p> <ul> <li><a href="https://atlasphp.io">Atlas</a></li> <li><a href="https://github.com/auraphp/Aura.Sql">Aura SQL</a></li> <li><a href="https://www.doctrine-project.org/projects/dbal.html">Doctrine2 DBAL</a></li> <li><a href="https://medoo.in/">Medoo</a></li> <li><a href="https://propelorm.org/">Propel</a></li> <li><a href="https://docs.laminas.dev/laminas-db/">laminas-db</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="templating"> <h1 id="templating_title">Templating</h1> <p>Templates provide a convenient way of separating your controller and domain logic from your presentation logic. Templates typically contain the HTML of your application, but may also be used for other formats, such as XML. Templates are often referred to as “views”, which make up <strong>part of</strong> the second component of the <a href="/pages/Design-Patterns.html#model-view-controller">model–view–controller</a> (MVC) software architecture pattern.</p> </section> <section class="chapter" id="templating_benefits"> <h2 id="templating_benefits_title">Benefits</h2> <p>The main benefit to using templates is the clear separation they create between the presentation logic and the rest of your application. Templates have the sole responsibility of displaying formatted content. They are not responsible for data lookup, persistence or other more complex tasks. This leads to cleaner, more readable code which is especially helpful in a team environment where developers work on the server-side code (controllers, models) and designers work on the client-side code (markup).</p> <p>Templates also improve the organization of presentation code. Templates are typically placed in a “views” folder, each defined within a single file. This approach encourages code reuse where larger blocks of code are broken into smaller, reusable pieces, often called partials. For example, your site header and footer can each be defined as templates, which are then included before and after each page template.</p> <p>Finally, depending on the library you use, templates can offer more security by automatically escaping user-generated content. Some libraries even offer sand-boxing, where template designers are only given access to white-listed variables and functions.</p> </section> <section class="chapter" id="plain_php_templates"> <h2 id="plain_php_templates_title">Plain PHP Templates</h2> <p>Plain PHP templates are simply templates that use native PHP code. They are a natural choice since PHP is actually a template language itself. That simply means that you can combine PHP code within other code, like HTML. This is beneficial to PHP developers as there is no new syntax to learn, they know the functions available to them, and their code editors already have PHP syntax highlighting and auto-completion built-in. Further, plain PHP templates tend to be very fast as no compiling stage is required.</p> <p>Every modern PHP framework employs some kind of template system, most of which use plain PHP by default. Outside of frameworks, libraries like <a href="https://platesphp.com/">Plates</a> or <a href="https://github.com/auraphp/Aura.View">Aura.View</a> make working with plain PHP templates easier by offering modern template functionality such as inheritance, layouts and extensions.</p> <h3 id="simple-example-of-a-plain-php-template">Simple example of a plain PHP template</h3> <p>Using the <a href="https://platesphp.com/">Plates</a> library.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="c1">// user_profile.php ?></span> <span class="o"><?</span><span class="n">php</span> <span class="nv">$this</span><span class="o">-></span><span class="nf">insert</span><span class="p">(</span><span class="s1">'header'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'title'</span> <span class="o">=></span> <span class="s1">'User Profile'</span><span class="p">])</span> <span class="cp">?></span> <span class="nt"><h1></span>User Profile<span class="nt"></h1></span> <span class="nt"><p></span>Hello, <span class="cp"><?=</span><span class="nv">$this</span><span class="o">-></span><span class="nf">escape</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span><span class="cp">?></span><span class="nt"></p></span> <span class="cp"><?php</span> <span class="nv">$this</span><span class="o">-></span><span class="nf">insert</span><span class="p">(</span><span class="s1">'footer'</span><span class="p">)</span> <span class="cp">?></span></code></pre></figure> <h3 id="example-of-plain-php-templates-using-inheritance">Example of plain PHP templates using inheritance</h3> <p>Using the <a href="https://platesphp.com/">Plates</a> library.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="c1">// template.php ?></span> <span class="o"><</span><span class="n">html</span><span class="o">></span> <span class="o"><</span><span class="n">head</span><span class="o">></span> <span class="o"><</span><span class="n">title</span><span class="o">><?=</span><span class="nv">$title</span><span class="cp">?></span><span class="nt"></title></span> <span class="nt"></head></span> <span class="nt"><body></span> <span class="nt"><main></span> <span class="cp"><?=</span><span class="nv">$this</span><span class="o">-></span><span class="nf">section</span><span class="p">(</span><span class="s1">'content'</span><span class="p">)</span><span class="cp">?></span> <span class="nt"></main></span> <span class="nt"></body></span> <span class="nt"></html></span></code></pre></figure> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="c1">// user_profile.php ?></span> <span class="o"><?</span><span class="n">php</span> <span class="nv">$this</span><span class="o">-></span><span class="nf">layout</span><span class="p">(</span><span class="s1">'template'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'title'</span> <span class="o">=></span> <span class="s1">'User Profile'</span><span class="p">])</span> <span class="cp">?></span> <span class="nt"><h1></span>User Profile<span class="nt"></h1></span> <span class="nt"><p></span>Hello, <span class="cp"><?=</span><span class="nv">$this</span><span class="o">-></span><span class="nf">escape</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span><span class="cp">?></span><span class="nt"></p></span></code></pre></figure> </section> <section class="chapter" id="compiled_templates"> <h2 id="compiled_templates_title">Compiled Templates</h2> <p>While PHP has evolved into a mature, object oriented language, it <a href="http://fabien.potencier.org/templating-engines-in-php.html">hasn’t improved much</a> as a templating language. Compiled templates, like <a href="https://twig.symfony.com/">Twig</a>, <a href="https://github.com/box/brainy">Brainy</a>, or <a href="https://www.smarty.net/">Smarty</a>*, fill this void by offering a new syntax that has been geared specifically to templating. From automatic escaping, to inheritance and simplified control structures, compiled templates are designed to be easier to write, cleaner to read and safer to use. Compiled templates can even be shared across different languages, <a href="https://mustache.github.io/">Mustache</a> being a good example of this. Since these templates must be compiled there is a slight performance hit, however this is very minimal when proper caching is used.</p> <p><em>*While Smarty offers automatic escaping, this feature is NOT enabled by default.</em></p> <h3 id="simple-example-of-a-compiled-template">Simple example of a compiled template</h3> <p>Using the <a href="https://twig.symfony.com/">Twig</a> library.</p> <figure class="highlight"><pre><code class="language-html-jinja" data-lang="html+jinja">{% include 'header.html' with {'title': 'User Profile'} %} <h1>User Profile</h1> <p>Hello, {{ name }}</p> {% include 'footer.html' %}</code></pre></figure> <h3 id="example-of-compiled-templates-using-inheritance">Example of compiled templates using inheritance</h3> <p>Using the <a href="https://twig.symfony.com/">Twig</a> library.</p> <figure class="highlight"><pre><code class="language-html-jinja" data-lang="html+jinja">// template.html <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <main> {% block content %}{% endblock %} </main> </body> </html></code></pre></figure> <figure class="highlight"><pre><code class="language-html-jinja" data-lang="html+jinja">// user_profile.html {% extends "template.html" %} {% block title %}User Profile{% endblock %} {% block content %} <h1>User Profile</h1> <p>Hello, {{ name }}</p> {% endblock %}</code></pre></figure> </section> <section class="chapter" id="templating_further_reading"> <h2 id="templating_further_reading_title">Further Reading</h2> <h3 id="articles--tutorials">Articles & Tutorials</h3> <ul> <li><a href="http://fabien.potencier.org/templating-engines-in-php.html">Templating Engines in PHP</a></li> <li><a href="https://code.tutsplus.com/tutorials/an-introduction-to-views-templating-in-codeigniter--net-25648">An Introduction to Views & Templating in CodeIgniter</a></li> <li><a href="https://www.smashingmagazine.com/2011/10/getting-started-with-php-templating/">Getting Started With PHP Templating</a></li> <li><a href="https://code.tutsplus.com/tutorials/roll-your-own-templating-system-in-php--net-16596">Roll Your Own Templating System in PHP</a></li> <li><a href="https://laracasts.com/series/laravel-from-scratch/episodes/7">Master Pages</a></li> <li><a href="https://code.tutsplus.com/tutorials/working-with-templates-in-symfony-2--cms-21172">Working With Templates in Symfony 2</a></li> <li><a href="https://github.com/box/brainy/wiki/Writing-Safe-Templates">Writing Safer Templates</a></li> </ul> <h3 id="libraries">Libraries</h3> <ul> <li><a href="https://github.com/auraphp/Aura.View">Aura.View</a> <em>(native)</em></li> <li><a href="https://laravel.com/docs/blade">Blade</a> <em>(compiled, framework specific)</em></li> <li><a href="https://github.com/box/brainy">Brainy</a> <em>(compiled)</em></li> <li><a href="https://github.com/nette/latte">Latte</a> <em>(compiled)</em></li> <li><a href="https://github.com/bobthecow/mustache.php">Mustache</a> <em>(compiled)</em></li> <li><a href="https://phptal.org/">PHPTAL</a> <em>(compiled)</em></li> <li><a href="https://platesphp.com/">Plates</a> <em>(native)</em></li> <li><a href="https://www.smarty.net/">Smarty</a> <em>(compiled)</em></li> <li><a href="https://twig.symfony.com/">Twig</a> <em>(compiled)</em></li> <li><a href="https://docs.laminas.dev/laminas-view/">laminas-view</a> <em>(native, framework specific)</em></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="errors_and_exceptions"> <h1 id="errors_and_exceptions_title">Errors and Exceptions</h1> </section> <section class="chapter" id="errors"> <h2 id="errors_title">Errors</h2> <p>In many “exception-heavy” programming languages, whenever anything goes wrong an exception will be thrown. This is certainly a viable way to do things, but PHP is an “exception-light” programming language. While it does have exceptions and more of the core is starting to use them when working with objects, most of PHP itself will try to keep processing regardless of what happens, unless a fatal error occurs.</p> <p>For example:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="gp">$</span><span class="w"> </span>php <span class="nt">-a</span> <span class="gp">php ></span><span class="w"> </span><span class="nb">echo</span> <span class="nv">$foo</span><span class="p">;</span> <span class="go">Notice: Undefined variable: foo in php shell code on line 1</span></code></pre></figure> <p>This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from “exception-heavy” languages, because referencing a missing variable in Python for example will throw an exception:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="gp">$</span><span class="w"> </span>python <span class="gp">></span><span class="o">>></span> print foo <span class="go">Traceback (most recent call last): </span><span class="gp"> File "<stdin></span><span class="s2">", line 1, in <module> </span><span class="go">NameError: name 'foo' is not defined</span></code></pre></figure> <p>The only real difference is that Python will freak out over any small thing, so that developers can be super sure any potential issue or edge-case is caught, whereas PHP will keep on processing unless something extreme happens, at which point it will throw an error and report it.</p> <h3 id="error-severity">Error Severity</h3> <p>PHP has several levels of error severity. The three most common types of messages are errors, notices and warnings. These have different levels of severity; <code class="language-plaintext highlighter-rouge">E_ERROR</code>, <code class="language-plaintext highlighter-rouge">E_NOTICE</code>, and <code class="language-plaintext highlighter-rouge">E_WARNING</code>. Errors are fatal run-time errors and are usually caused by faults in your code and need to be fixed as they’ll cause PHP to stop executing. Notices are advisory messages caused by code that may or may not cause problems during the execution of the script, execution is not halted. Warnings are non-fatal errors, execution of the script will not be halted.</p> <p>Another type of error message reported at compile time are <code class="language-plaintext highlighter-rouge">E_STRICT</code> messages. These messages are used to suggest changes to your code to help ensure best interoperability and forward compatibility with upcoming versions of PHP.</p> <h3 id="changing-phps-error-reporting-behaviour">Changing PHP’s Error Reporting Behaviour</h3> <p>Error Reporting can be changed by using PHP settings and/or PHP function calls. Using the built in PHP function <code class="language-plaintext highlighter-rouge">error_reporting()</code> you can set the level of errors for the duration of the script execution by passing one of the predefined error level constants, meaning if you only want to see Errors and Warnings - but not Notices - then you can configure that:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="nb">error_reporting</span><span class="p">(</span><span class="kc">E_ERROR</span> <span class="o">|</span> <span class="kc">E_WARNING</span><span class="p">);</span></code></pre></figure> <p>You can also control whether or not errors are displayed to the screen (good for development) or hidden, and logged (good for production). For more information on this check out the <a href="/#error_reporting">Error Reporting</a> section.</p> <h3 id="inline-error-suppression">Inline Error Suppression</h3> <p>You can also tell PHP to suppress specific errors with the Error Control Operator <code class="language-plaintext highlighter-rouge">@</code>. You put this operator at the beginning of an expression, and any error that’s a direct result of the expression is silenced.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="k">echo</span> <span class="o">@</span><span class="nv">$foo</span><span class="p">[</span><span class="s1">'bar'</span><span class="p">];</span></code></pre></figure> <p>This will output <code class="language-plaintext highlighter-rouge">$foo['bar']</code> if it exists, but will simply return a null and print nothing if the variable <code class="language-plaintext highlighter-rouge">$foo</code> or <code class="language-plaintext highlighter-rouge">'bar'</code> key does not exist. Without the error control operator, this expression could create a <code class="language-plaintext highlighter-rouge">PHP Notice: Undefined variable: foo</code> or <code class="language-plaintext highlighter-rouge">PHP Notice: Undefined index: bar</code> error.</p> <p>This might seem like a good idea, but there are a few undesirable tradeoffs. PHP handles expressions using an <code class="language-plaintext highlighter-rouge">@</code> in a less performant way than expressions without an <code class="language-plaintext highlighter-rouge">@</code>. Premature optimization may be the root of all programming arguments, but if performance is particularly important for your application/library it’s important to understand the error control operator’s performance implications.</p> <p>Secondly, the error control operator <strong>completely</strong> swallows the error. The error is not displayed, and the error is not sent to the error log. Also, stock/production PHP systems have no way to turn off the error control operator. While you may be correct that the error you’re seeing is harmless, a different, less harmless error will be just as silent.</p> <p>If there’s a way to avoid the error suppression operator, you should consider it. For example, our code above could be rewritten like this:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="c1">// Null Coalescing Operator</span> <span class="k">echo</span> <span class="nv">$foo</span><span class="p">[</span><span class="s1">'bar'</span><span class="p">]</span> <span class="o">??</span> <span class="s1">''</span><span class="p">;</span></code></pre></figure> <p>One instance where error suppression might make sense is where <code class="language-plaintext highlighter-rouge">fopen()</code> fails to find a file to load. You could check for the existence of the file before you try to load it, but if the file is deleted after the check and before the <code class="language-plaintext highlighter-rouge">fopen()</code> (which might sound impossible, but it can happen) then <code class="language-plaintext highlighter-rouge">fopen()</code> will return false <em>and</em> throw an error. This is potentially something PHP should resolve, but is one case where error suppression might seem like the only valid solution.</p> <p>Earlier we mentioned there’s no way in a stock PHP system to turn off the error control operator. However, <a href="https://xdebug.org/docs/basic">Xdebug</a> has an <code class="language-plaintext highlighter-rouge">xdebug.scream</code> ini setting which will disable the error control operator. You can set this via your <code class="language-plaintext highlighter-rouge">php.ini</code> file with the following.</p> <figure class="highlight"><pre><code class="language-ini" data-lang="ini"><span class="py">xdebug.scream</span> <span class="p">=</span> <span class="s">On</span></code></pre></figure> <p>You can also set this value at runtime with the <code class="language-plaintext highlighter-rouge">ini_set</code> function</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="nb">ini_set</span><span class="p">(</span><span class="s1">'xdebug.scream'</span><span class="p">,</span> <span class="s1">'1'</span><span class="p">)</span></code></pre></figure> <p>This is most useful when you’re debugging code and suspect an informative error is suppressed. Use scream with care, and as a temporary debugging tool. There’s lots of PHP library code that may not work with the error control operator disabled.</p> <ul> <li><a href="https://www.php.net/language.operators.errorcontrol">Error Control Operators</a></li> <li><a href="https://www.sitepoint.com/">SitePoint</a></li> <li><a href="https://xdebug.org/docs/basic">Xdebug</a></li> </ul> <h3 id="errorexception">ErrorException</h3> <p>PHP is perfectly capable of being an “exception-heavy” programming language, and only requires a few lines of code to make the switch. Basically you can throw your “errors” as “exceptions” using the <code class="language-plaintext highlighter-rouge">ErrorException</code> class, which extends the <code class="language-plaintext highlighter-rouge">Exception</code> class.</p> <p>This is a common practice implemented by a large number of modern frameworks such as Symfony and Laravel. In debug mode <em>(or dev mode)</em> both of these frameworks will display a nice and clean <em>stack trace</em>.</p> <p>There are also some packages available for better error and exception handling and reporting. Like <a href="https://filp.github.io/whoops/">Whoops!</a>, which comes with the default installation of Laravel and can be used in any framework as well.</p> <p>By throwing errors as exceptions in development you can handle them better than the usual result, and if you see an exception during development you can wrap it in a catch statement with specific instructions on how to handle the situation. Each exception you catch instantly makes your application that little bit more robust.</p> <p>More information on this and details on how to use <code class="language-plaintext highlighter-rouge">ErrorException</code> with error handling can be found at <a href="https://www.php.net/class.errorexception">ErrorException Class</a>.</p> <ul> <li><a href="https://www.php.net/language.operators.errorcontrol">Error Control Operators</a></li> <li><a href="https://www.php.net/errorfunc.constants">Predefined Constants for Error Handling</a></li> <li><a href="https://www.php.net/function.error-reporting"><code class="language-plaintext highlighter-rouge">error_reporting()</code></a></li> <li><a href="/#error_reporting">Reporting</a></li> </ul> </section> <section class="chapter" id="exceptions"> <h2 id="exceptions_title">Exceptions</h2> <p>Exceptions are a standard part of most popular programming languages, but they are often overlooked by PHP programmers. Languages like Ruby are extremely Exception heavy, so whenever something goes wrong such as a HTTP request failing, or a DB query goes wrong, or even if an image asset could not be found, Ruby (or the gems being used) will throw an exception to the screen meaning you instantly know there is a mistake.</p> <p>PHP itself is fairly lax with this, and a call to <code class="language-plaintext highlighter-rouge">file_get_contents()</code> will usually just get you a <code class="language-plaintext highlighter-rouge">FALSE</code> and a warning. Many older PHP frameworks like CodeIgniter will just return a false, log a message to their proprietary logs and maybe let you use a method like <code class="language-plaintext highlighter-rouge">$this->upload->get_error()</code> to see what went wrong. The problem here is that you have to go looking for a mistake and check the docs to see what the error method is for this class, instead of having it made extremely obvious.</p> <p>Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you stop another developer from being able to dynamically handle that error. Exceptions should be thrown to make a developer aware of an error; they then can choose how to handle this. E.g.:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="nv">$email</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Fuel\Email</span><span class="p">;</span> <span class="nv">$email</span><span class="o">-></span><span class="nf">subject</span><span class="p">(</span><span class="s1">'My Subject'</span><span class="p">);</span> <span class="nv">$email</span><span class="o">-></span><span class="nf">body</span><span class="p">(</span><span class="s1">'How the heck are you?'</span><span class="p">);</span> <span class="nv">$email</span><span class="o">-></span><span class="nf">to</span><span class="p">(</span><span class="s1">'guy@example.com'</span><span class="p">,</span> <span class="s1">'Some Guy'</span><span class="p">);</span> <span class="k">try</span> <span class="p">{</span> <span class="nv">$email</span><span class="o">-></span><span class="nf">send</span><span class="p">();</span> <span class="p">}</span> <span class="k">catch</span><span class="p">(</span><span class="nc">Fuel\Email\ValidationFailedException</span> <span class="nv">$e</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// The validation failed</span> <span class="p">}</span> <span class="k">catch</span><span class="p">(</span><span class="nc">Fuel\Email\SendingFailedException</span> <span class="nv">$e</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// The driver could not send the email</span> <span class="p">}</span> <span class="k">finally</span> <span class="p">{</span> <span class="c1">// Executed regardless of whether an exception has been thrown, and before normal execution resumes</span> <span class="p">}</span></code></pre></figure> <h3 id="spl-exceptions">SPL Exceptions</h3> <p>The generic <code class="language-plaintext highlighter-rouge">Exception</code> class provides very little debugging context for the developer; however, to remedy this, it is possible to create a specialized <code class="language-plaintext highlighter-rouge">Exception</code> type by sub-classing the generic <code class="language-plaintext highlighter-rouge">Exception</code> class:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="kd">class</span> <span class="nc">ValidationException</span> <span class="kd">extends</span> <span class="nc">Exception</span> <span class="p">{}</span></code></pre></figure> <p>This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to the creation of a <em>lot</em> of custom Exceptions, some of which could have been avoided using the SPL Exceptions provided in the <a href="/#standard_php_library">SPL extension</a>.</p> <p>If for example you use the <code class="language-plaintext highlighter-rouge">__call()</code> Magic Method and an invalid method is requested then instead of throwing a standard Exception which is vague, or creating a custom Exception just for that, you could just <code class="language-plaintext highlighter-rouge">throw new BadMethodCallException;</code>.</p> <ul> <li><a href="https://www.php.net/language.exceptions">Read about Exceptions</a></li> <li><a href="https://www.php.net/spl.exceptions">Read about SPL Exceptions</a></li> <li><a href="https://www.brandonsavage.net/exceptional-php-nesting-exceptions-in-php/">Nesting Exceptions In PHP</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="security"> <h1 id="security_title">Security</h1> <p>The best resource I’ve found on PHP security is <a href="https://paragonie.com/blog/2017/12/2018-guide-building-secure-php-software">The 2018 Guide to Building Secure PHP Software</a> by <a href="https://paragonie.com/">Paragon Initiative</a>.</p> </section> <section class="chapter" id="web_application_security"> <h2 id="web_application_security_title">Web Application Security</h2> <p>It is very important for every PHP developer to learn <a href="https://paragonie.com/blog/2015/08/gentle-introduction-application-security">the basics of web application security</a>, which can be broken down into a handful of broad topics:</p> <ol> <li>Code-data separation. <ul> <li>When data is executed as code, you get SQL Injection, Cross-Site Scripting, Local/Remote File Inclusion, etc.</li> <li>When code is printed as data, you get information leaks (source code disclosure or, in the case of C programs, enough information to bypass <a href="https://www.techtarget.com/searchsecurity/definition/address-space-layout-randomization-ASLR">ASLR</a>).</li> </ul> </li> <li>Application logic. <ul> <li>Missing authentication or authorization controls.</li> <li>Input validation.</li> </ul> </li> <li>Operating environment. <ul> <li>PHP versions.</li> <li>Third party libraries.</li> <li>The operating system.</li> </ul> </li> <li>Cryptography weaknesses. <ul> <li><a href="https://paragonie.com/blog/2016/01/on-design-and-implementation-stealth-backdoor-for-web-applications">Weak random numbers</a>.</li> <li><a href="https://paragonie.com/blog/2015/05/using-encryption-and-authentication-correctly">Chosen-ciphertext attacks</a>.</li> <li><a href="https://blog.ircmaxell.com/2014/11/its-all-about-time.html">Side-channel information leaks</a>.</li> </ul> </li> </ol> <p>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 <a href="https://www.owasp.org/">The Open Web Application Security Project</a> (OWASP) have compiled a comprehensive list of known security issues and methods to protect yourself against them. This is a must read for the security-conscious developer. <a href="https://phpsecurity.readthedocs.io/en/latest/index.html">Survive The Deep End: PHP Security</a> by Padraic Brady is also another good web application security guide for PHP.</p> <ul> <li><a href="https://www.owasp.org/index.php/Guide_Table_of_Contents">Read the OWASP Security Guide</a></li> </ul> </section> <section class="chapter" id="password_hashing"> <h2 id="password_hashing_title">Password Hashing</h2> <p>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.</p> <p>It is important that you properly <a href="https://wikipedia.org/wiki/Cryptographic_hash_function"><em>hash</em></a> passwords before storing them. Hashing and encrypting are <a href="https://paragonie.com/blog/2015/08/you-wouldnt-base64-a-password-cryptography-decoded">two very different things</a> that often get confused.</p> <p>Hashing is an irreversible, one-way function. This produces a fixed-length string that cannot be feasibly reversed. This means you can compare a hash against another to determine if they both came from the same source string, but you cannot determine the original string. If passwords are not hashed and your database is accessed by an unauthorized third-party, all user accounts are now compromised.</p> <p>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.</p> <p>Passwords should also be individually <a href="https://wikipedia.org/wiki/Salt_(cryptography)"><em>salted</em></a> by adding a random string to each password before hashing. This prevents dictionary attacks and the use of “rainbow tables” (a reverse list of cryptographic hashes for common passwords.)</p> <p>Hashing and salting are vital as often users use the same password for multiple services and password quality can be poor.</p> <p>Additionally, you should use <a href="https://paragonie.com/blog/2016/02/how-safely-store-password-in-2016">a specialized <em>password hashing</em> algorithm</a> 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:</p> <ul> <li>Argon2 (available in PHP 7.2 and newer)</li> <li>Scrypt</li> <li><strong>Bcrypt</strong> (PHP provides this one for you; see below)</li> <li>PBKDF2 with HMAC-SHA256 or HMAC-SHA512</li> </ul> <p>Fortunately, nowadays PHP makes this easy.</p> <p><strong>Hashing passwords with <code class="language-plaintext highlighter-rouge">password_hash</code></strong></p> <p>In PHP 5.5 <code class="language-plaintext highlighter-rouge">password_hash()</code> was introduced. At this time it is using BCrypt, the strongest algorithm currently supported by PHP. It will be updated in the future to support more algorithms as needed though. The <code class="language-plaintext highlighter-rouge">password_compat</code> library was created to provide forward compatibility for PHP >= 5.3.7.</p> <p>Below we hash a string, and then check the hash against a new string. Because our two source strings are different (‘secret-password’ vs. ‘bad-password’) this login will fail.</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="k">require</span> <span class="s1">'password.php'</span><span class="p">;</span> <span class="nv">$passwordHash</span> <span class="o">=</span> <span class="nb">password_hash</span><span class="p">(</span><span class="s1">'secret-password'</span><span class="p">,</span> <span class="no">PASSWORD_DEFAULT</span><span class="p">);</span> <span class="k">if</span> <span class="p">(</span><span class="nb">password_verify</span><span class="p">(</span><span class="s1">'bad-password'</span><span class="p">,</span> <span class="nv">$passwordHash</span><span class="p">))</span> <span class="p">{</span> <span class="c1">// Correct Password</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="c1">// Wrong password</span> <span class="p">}</span></code></pre></figure> <p><code class="language-plaintext highlighter-rouge">password_hash()</code> takes care of password salting for you. The salt is stored, along with the algorithm and “cost”, as part of the hash. <code class="language-plaintext highlighter-rouge">password_verify()</code> extracts this to determine how to check the password, so you don’t need a separate database field to store your salts.</p> <ul> <li><a href="https://www.php.net/function.password-hash">Learn about <code class="language-plaintext highlighter-rouge">password_hash()</code></a></li> <li><a href="https://github.com/ircmaxell/password_compat"><code class="language-plaintext highlighter-rouge">password_compat</code> for PHP >= 5.3.7 && < 5.5</a></li> <li><a href="https://wikipedia.org/wiki/Cryptographic_hash_function">Learn about hashing in regards to cryptography</a></li> <li><a href="https://wikipedia.org/wiki/Salt_(cryptography)">Learn about salts</a></li> <li><a href="https://wiki.php.net/rfc/password_hash">PHP <code class="language-plaintext highlighter-rouge">password_hash()</code> RFC</a></li> </ul> </section> <section class="chapter" id="data_filtering"> <h2 id="data_filtering_title">Data Filtering</h2> <p>Never ever (ever) trust foreign input introduced to your PHP code. Always sanitize and validate foreign input before using it in code. The <code class="language-plaintext highlighter-rouge">filter_var()</code> and <code class="language-plaintext highlighter-rouge">filter_input()</code> functions can sanitize text and validate text formats (e.g. email addresses).</p> <p>Foreign input can be anything: <code class="language-plaintext highlighter-rouge">$_GET</code> and <code class="language-plaintext highlighter-rouge">$_POST</code> form input data, some values in the <code class="language-plaintext highlighter-rouge">$_SERVER</code> superglobal, and the HTTP request body via <code class="language-plaintext highlighter-rouge">fopen('php://input', 'r')</code>. Remember, foreign input is not limited to form data submitted by the user. Uploaded and downloaded files, session values, cookie data, and data from third-party web services are foreign input, too.</p> <p>While foreign data can be stored, combined, and accessed later, it is still foreign input. Every time you process, output, concatenate, or include data in your code, ask yourself if the data is filtered properly and can it be trusted.</p> <p>Data may be <em>filtered</em> differently based on its purpose. For example, when unfiltered foreign input is passed into HTML page output, it can execute HTML and JavaScript on your site! This is known as Cross-Site Scripting (XSS) and can be a very dangerous attack. One way to avoid XSS is to sanitize all user-generated data before outputting it to your page by removing HTML tags with the <code class="language-plaintext highlighter-rouge">strip_tags()</code> function or escaping characters with special meaning into their respective HTML entities with the <code class="language-plaintext highlighter-rouge">htmlentities()</code> or <code class="language-plaintext highlighter-rouge">htmlspecialchars()</code> functions.</p> <p>Another example is passing options to be executed on the command line. This can be extremely dangerous (and is usually a bad idea), but you can use the built-in <code class="language-plaintext highlighter-rouge">escapeshellarg()</code> function to sanitize the executed command’s arguments.</p> <p>One last example is accepting foreign input to determine a file to load from the filesystem. This can be exploited by changing the filename to a file path. You need to remove <code class="language-plaintext highlighter-rouge">"/"</code>, <code class="language-plaintext highlighter-rouge">"../"</code>, <a href="https://www.php.net/security.filesystem.nullbytes">null bytes</a>, or other characters from the file path so it can’t load hidden, non-public, or sensitive files.</p> <ul> <li><a href="https://www.php.net/book.filter">Learn about data filtering</a></li> <li><a href="https://www.php.net/function.filter-var">Learn about <code class="language-plaintext highlighter-rouge">filter_var</code></a></li> <li><a href="https://www.php.net/function.filter-input">Learn about <code class="language-plaintext highlighter-rouge">filter_input</code></a></li> <li><a href="https://www.php.net/security.filesystem.nullbytes">Learn about handling null bytes</a></li> </ul> <h3 id="sanitization">Sanitization</h3> <p>Sanitization removes (or escapes) illegal or unsafe characters from foreign input.</p> <p>For example, you should sanitize foreign input before including the input in HTML or inserting it into a raw SQL query. When you use bound parameters with <a href="#databases">PDO</a>, it will sanitize the input for you.</p> <p>Sometimes it is required to allow some safe HTML tags in the input when including it in the HTML page. This is very hard to do and many avoid it by using other more restricted formatting like Markdown or BBCode, although whitelisting libraries like <a href="http://htmlpurifier.org/">HTML Purifier</a> exist for this reason.</p> <p><a href="https://www.php.net/filter.filters.sanitize">See Sanitization Filters</a></p> <h3 id="unserialization">Unserialization</h3> <p>It is dangerous to <code class="language-plaintext highlighter-rouge">unserialize()</code> data from users or other untrusted sources. Doing so can allow malicious users to instantiate objects (with user-defined properties) whose destructors will be executed, <strong>even if the objects themselves aren’t used</strong>. You should therefore avoid unserializing untrusted data.</p> <p>Use a safe, standard data interchange format such as JSON (via <a href="https://www.php.net/manual/function.json-decode.php"><code class="language-plaintext highlighter-rouge">json_decode</code></a> and <a href="https://www.php.net/manual/function.json-encode.php"><code class="language-plaintext highlighter-rouge">json_encode</code></a>) if you need to pass serialized data to the user.</p> <h3 id="validation">Validation</h3> <p>Validation ensures that foreign input is what you expect. For example, you may want to validate an email address, a phone number, or age when processing a registration submission.</p> <p><a href="https://www.php.net/filter.filters.validate">See Validation Filters</a></p> </section> <section class="chapter" id="configuration_files"> <h2 id="configuration_files_title">Configuration Files</h2> <p>When creating configuration files for your applications, best practices recommend that one of the following methods be followed:</p> <ul> <li>It is recommended that you store your configuration information where it cannot be accessed directly and pulled in via the file system.</li> <li>If you must store your configuration files in the document root, name the files with a <code class="language-plaintext highlighter-rouge">.php</code> extension. This ensures that, even if the script is accessed directly, it will not be output as plain text.</li> <li>Information in configuration files should be protected accordingly, either through encryption or group/user file system permissions.</li> <li>It is a good idea to ensure that you do not commit configuration files containing sensitive information e.g. passwords or API tokens to source control.</li> </ul> </section> <section class="chapter" id="register_globals"> <h2 id="register_globals_title">Register Globals</h2> <p><strong>NOTE:</strong> As of PHP 5.4.0 the <code class="language-plaintext highlighter-rouge">register_globals</code> setting has been removed and can no longer be used. This is only included as a warning for anyone in the process of upgrading a legacy application.</p> <p>When enabled, the <code class="language-plaintext highlighter-rouge">register_globals</code> configuration setting makes several types of variables (including ones from <code class="language-plaintext highlighter-rouge">$_POST</code>, <code class="language-plaintext highlighter-rouge">$_GET</code> and <code class="language-plaintext highlighter-rouge">$_REQUEST</code>) available in the global scope of your application. This can easily lead to security issues as your application cannot effectively tell where the data is coming from.</p> <p>For example: <code class="language-plaintext highlighter-rouge">$_GET['foo']</code> would be available via <code class="language-plaintext highlighter-rouge">$foo</code>, which can override variables that have been declared.</p> <p>If you are using PHP < 5.4.0 <strong>make sure</strong> that <code class="language-plaintext highlighter-rouge">register_globals</code> is <strong>off</strong>.</p> </section> <section class="chapter" id="error_reporting"> <h2 id="error_reporting_title">Error Reporting</h2> <p>Error logging can be useful in finding the problem spots in your application, but it can also expose information about the structure of your application to the outside world. To effectively protect your application from issues that could be caused by the output of these messages, you need to configure your server differently in development versus production (live).</p> <h3 id="development">Development</h3> <p>To show every possible error during <strong>development</strong>, configure the following settings in your <code class="language-plaintext highlighter-rouge">php.ini</code>:</p> <figure class="highlight"><pre><code class="language-ini" data-lang="ini"><span class="py">display_errors</span> <span class="p">=</span> <span class="s">On</span> <span class="py">display_startup_errors</span> <span class="p">=</span> <span class="s">On</span> <span class="py">error_reporting</span> <span class="p">=</span> <span class="s">-1</span> <span class="py">log_errors</span> <span class="p">=</span> <span class="s">On</span></code></pre></figure> <blockquote> <p>Passing in the value <code class="language-plaintext highlighter-rouge">-1</code> will show every possible error, even when new levels and constants are added in future PHP versions. The <code class="language-plaintext highlighter-rouge">E_ALL</code> constant also behaves this way as of PHP 5.4. - <a href="https://www.php.net/function.error-reporting">php.net</a></p> </blockquote> <p>The <code class="language-plaintext highlighter-rouge">E_STRICT</code> error level constant was introduced in 5.3.0 and is not part of <code class="language-plaintext highlighter-rouge">E_ALL</code>, however it became part of <code class="language-plaintext highlighter-rouge">E_ALL</code> in 5.4.0. What does this mean? In terms of reporting every possible error in version 5.3 it means you must use either <code class="language-plaintext highlighter-rouge">-1</code> or <code class="language-plaintext highlighter-rouge">E_ALL | E_STRICT</code>.</p> <p><strong>Reporting every possible error by PHP version</strong></p> <ul> <li>< 5.3 <code class="language-plaintext highlighter-rouge">-1</code> or <code class="language-plaintext highlighter-rouge">E_ALL</code></li> <li> 5.3 <code class="language-plaintext highlighter-rouge">-1</code> or <code class="language-plaintext highlighter-rouge">E_ALL | E_STRICT</code></li> <li>> 5.3 <code class="language-plaintext highlighter-rouge">-1</code> or <code class="language-plaintext highlighter-rouge">E_ALL</code></li> </ul> <h3 id="production">Production</h3> <p>To hide errors on your <strong>production</strong> environment, configure your <code class="language-plaintext highlighter-rouge">php.ini</code> as:</p> <figure class="highlight"><pre><code class="language-ini" data-lang="ini"><span class="py">display_errors</span> <span class="p">=</span> <span class="s">Off</span> <span class="py">display_startup_errors</span> <span class="p">=</span> <span class="s">Off</span> <span class="py">error_reporting</span> <span class="p">=</span> <span class="s">E_ALL</span> <span class="py">log_errors</span> <span class="p">=</span> <span class="s">On</span></code></pre></figure> <p>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:</p> <ul> <li><a href="https://www.php.net/errorfunc.configuration#ini.error-reporting">error_reporting</a></li> <li><a href="https://www.php.net/errorfunc.configuration#ini.display-errors">display_errors</a></li> <li><a href="https://www.php.net/errorfunc.configuration#ini.display-startup-errors">display_startup_errors</a></li> <li><a href="https://www.php.net/errorfunc.configuration#ini.log-errors">log_errors</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="testing"> <h1 id="testing_title">Testing</h1> <p>Writing automated tests for your PHP code is considered a best practice and can lead to well-built applications. Automated tests are a great tool for making sure your application does not break when you are making changes or adding new functionality and should not be ignored.</p> <p>There are several different types of testing tools (or frameworks) available for PHP, which use different approaches - all of which are trying to avoid manual testing and the need for large Quality Assurance teams, just to make sure recent changes didn’t break existing functionality.</p> </section> <section class="chapter" id="test_driven_development"> <h2 id="test_driven_development_title">Test Driven Development</h2> <p>From <a href="https://wikipedia.org/wiki/Test-driven_development">Wikipedia</a>:</p> <blockquote> <p>Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finally refactors the new code to acceptable standards. Kent Beck, who is credited with having developed or ‘rediscovered’ the technique, stated in 2003 that TDD encourages simple designs and inspires confidence.</p> </blockquote> <p>There are several different types of testing that you can do for your application:</p> <h3 id="unit-testing">Unit Testing</h3> <p>Unit Testing is a programming approach to ensure functions, classes and methods are working as expected, from the point you build them all the way through the development cycle. By checking values going in and out of various functions and methods, you can make sure the internal logic is working correctly. By using Dependency Injection and building “mock” classes and stubs you can verify that dependencies are correctly used for even better test coverage.</p> <p>When you create a class or function you should create a unit test for each behavior it must have. At a very basic level you should make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments. This will help ensure that when you make changes to this class or function later on in the development cycle that the old functionality continues to work as expected. The only alternative to this would be <code class="language-plaintext highlighter-rouge">var_dump()</code> in a test.php, which is no way to build an application - large or small.</p> <p>The other use for unit tests is contributing to open source. If you can write a test that shows broken functionality (i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If you run a project which accepts pull requests then you should suggest this as a requirement.</p> <p><a href="https://phpunit.de/">PHPUnit</a> is the de-facto testing framework for writing unit tests for PHP applications, but there are several alternatives:</p> <ul> <li><a href="https://github.com/atoum/atoum">atoum</a></li> <li><a href="https://github.com/kahlan/kahlan">Kahlan</a></li> <li><a href="https://peridot-php.github.io/">Peridot</a></li> <li><a href="https://pestphp.com/">Pest</a></li> <li><a href="https://github.com/simpletest/simpletest">SimpleTest</a></li> </ul> <h3 id="integration-testing">Integration Testing</h3> <p>From <a href="https://wikipedia.org/wiki/Integration_testing">Wikipedia</a>:</p> <blockquote> <p>Integration testing (sometimes called Integration and Testing, abbreviated “I&T”) is the phase in software testing in which individual software modules are combined and tested as a group. It occurs after unit testing and before validation testing. Integration testing takes as its input modules that have been unit tested, groups them in larger aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the integrated system ready for system testing.</p> </blockquote> <p>Many of the same tools that can be used for unit testing can be used for integration testing as many of the same principles are used.</p> <h3 id="functional-testing">Functional Testing</h3> <p>Sometimes also known as acceptance testing, functional testing consists of using tools to create automated tests that actually use your application instead of just verifying that individual units of code are behaving correctly and that individual units can speak to each other correctly. These tools typically work using real data and simulating actual users of the application.</p> <h4 id="functional-testing-tools">Functional Testing Tools</h4> <ul> <li><a href="https://www.selenium.dev/">Selenium</a></li> <li><a href="https://mink.behat.org/">Mink</a></li> <li><a href="https://codeception.com/">Codeception</a> is a full-stack testing framework that includes acceptance testing tools</li> <li><a href="https://github.com/MeltwaterArchive/storyplayer">Storyplayer</a> is a full-stack testing framework that includes support for creating and destroying test environments on demand</li> </ul> </section> <section class="chapter" id="behavior_driven_development"> <h2 id="behavior_driven_development_title">Behavior Driven Development</h2> <p>There are two different types of Behavior-Driven Development (BDD): SpecBDD and StoryBDD. SpecBDD focuses on technical behavior of code, while StoryBDD focuses on business or feature behaviors or interactions. PHP has frameworks for both types of BDD.</p> <p>With StoryBDD, you write human-readable stories that describe the behavior of your application. These stories can then be run as actual tests against your application. The framework used in PHP applications for StoryBDD is <a href="https://behat.org/">Behat</a>, which is inspired by Ruby’s <a href="https://cucumber.io/">Cucumber</a> project and implements the Gherkin DSL for describing feature behavior.</p> <p>With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing a function or method, you are describing how that function or method should behave. PHP offers the <a href="https://www.phpspec.net/">PHPSpec</a> framework for this purpose. This framework is inspired by the <a href="https://rspec.info/">RSpec project</a> for Ruby.</p> <h3 id="bdd-links">BDD Links</h3> <ul> <li><a href="https://behat.org/">Behat</a>, the StoryBDD framework for PHP, inspired by Ruby’s <a href="https://cucumber.io/">Cucumber</a> project;</li> <li><a href="https://www.phpspec.net/">PHPSpec</a>, the SpecBDD framework for PHP, inspired by Ruby’s <a href="https://rspec.info/">RSpec</a> project;</li> <li><a href="https://codeception.com/">Codeception</a> is a full-stack testing framework that uses BDD principles.</li> </ul> </section> <section class="chapter" id="complementary_testing_tools"> <h2 id="complementary_testing_tools_title">Complementary Testing Tools</h2> <p>Besides individual testing and behavior driven frameworks, there are also a number of generic frameworks and helper libraries useful for any preferred approach taken.</p> <h3 id="tool-links">Tool Links</h3> <ul> <li><a href="https://www.selenium.dev/">Selenium</a> is a browser automation tool which can be <a href="https://github.com/giorgiosironi/phpunit-selenium/">integrated with PHPUnit</a></li> <li><a href="https://github.com/padraic/mockery">Mockery</a> is a Mock Object Framework which can be integrated with <a href="https://phpunit.de/">PHPUnit</a> or <a href="https://www.phpspec.net/">PHPSpec</a></li> <li><a href="https://github.com/phpspec/prophecy">Prophecy</a> is a highly opinionated yet very powerful and flexible PHP object mocking framework. It’s integrated with <a href="https://www.phpspec.net/">PHPSpec</a> and can be used with <a href="https://phpunit.de/">PHPUnit</a>.</li> <li><a href="https://github.com/php-mock/php-mock">php-mock</a> is a library to help to mock PHP native functions.</li> <li><a href="https://github.com/infection/infection">Infection</a> is a PHP implementation of <a href="https://en.wikipedia.org/wiki/Mutation_testing">Mutation Testing</a> to help to measure the effectiveness of your tests.</li> <li><a href="https://github.com/Yoast/PHPUnit-Polyfills">PHPUnit Polyfills</a> is a library that allows for creating PHPUnit cross-version compatible tests when a test suite needs to run against a range of PHPUnit versions.</li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="servers_and_deployment"> <h1 id="servers_and_deployment_title">Servers and Deployment</h1> <p>PHP applications can be deployed and run on production web servers in a number of ways.</p> </section> <section class="chapter" id="platform_as_a_service"> <h2 id="platform_as_a_service_title">Platform as a Service (PaaS)</h2> <p>PaaS provides the system and network architecture necessary to run PHP applications on the web. This means little to no configuration for launching PHP applications or PHP frameworks.</p> <p>Recently PaaS has become a popular method for deploying, hosting, and scaling PHP applications of all sizes. You can find a list of <a href="#php_paas_providers">PHP PaaS “Platform as a Service” providers</a> in our <a href="#resources">resources section</a>.</p> </section> <section class="chapter" id="virtual_or_dedicated_servers"> <h2 id="virtual_or_dedicated_servers_title">Virtual or Dedicated Servers</h2> <p>If you are comfortable with systems administration, or are interested in learning it, virtual or dedicated servers give you complete control of your application’s production environment.</p> <h3 id="nginx-and-php-fpm">nginx and PHP-FPM</h3> <p>PHP, via PHP’s built-in FastCGI Process Manager (FPM), pairs really nicely with <a href="https://nginx.org/">nginx</a>, which is a lightweight, high-performance web server. It uses less memory than Apache and can better handle more concurrent requests. This is especially important on virtual servers that don’t have much memory to spare.</p> <ul> <li><a href="https://nginx.org/">Read more on nginx</a></li> <li><a href="https://www.php.net/install.fpm">Read more on PHP-FPM</a></li> <li><a href="https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/">Read more on setting up nginx and PHP-FPM securely</a></li> </ul> <h3 id="apache-and-php">Apache and PHP</h3> <p>PHP and Apache have a long history together. Apache is wildly configurable and has many available <a href="https://httpd.apache.org/docs/2.4/mod/">modules</a> to extend functionality. It is a popular choice for shared servers and an easy setup for PHP frameworks and open source apps like WordPress. Unfortunately, Apache uses more resources than nginx by default and cannot handle as many visitors at the same time.</p> <p>Apache has several possible configurations for running PHP. The most common and easiest to setup is the <a href="https://httpd.apache.org/docs/2.4/mod/prefork.html">prefork MPM</a> with <code class="language-plaintext highlighter-rouge">mod_php</code>. While it isn’t the most memory efficient, it is the simplest to get working and to use. This is probably the best choice if you don’t want to dig too deeply into the server administration aspects. Note that if you use <code class="language-plaintext highlighter-rouge">mod_php</code> you MUST use the prefork MPM.</p> <p>Alternatively, if you want to squeeze more performance and stability out of Apache then you can take advantage of the same FPM system as nginx and run the <a href="https://httpd.apache.org/docs/2.4/mod/worker.html">worker MPM</a> or <a href="https://httpd.apache.org/docs/2.4/mod/event.html">event MPM</a> with mod_fastcgi or mod_fcgid. This configuration will be significantly more memory efficient and much faster but it is more work to set up.</p> <p>If you are running Apache 2.4 or later, you can use <a href="https://httpd.apache.org/docs/current/mod/mod_proxy_fcgi.html">mod_proxy_fcgi</a> to get great performance that is easy to setup.</p> <ul> <li><a href="https://httpd.apache.org/">Read more on Apache</a></li> <li><a href="https://httpd.apache.org/docs/2.4/mod/mpm_common.html">Read more on Multi-Processing Modules</a></li> <li><a href="https://blogs.oracle.com/opal/post/php-fpm-fastcgi-process-manager-with-apache-2">Read more on mod_fastcgi</a></li> <li><a href="https://httpd.apache.org/mod_fcgid/">Read more on mod_fcgid</a></li> <li><a href="https://httpd.apache.org/docs/current/mod/mod_proxy_fcgi.html">Read more on mod_proxy_fcgi</a></li> <li><a href="https://serversforhackers.com/video/apache-and-php-fpm">Read more on setting up Apache and PHP-FPM with mod_proxy_fcgi</a></li> </ul> </section> <section class="chapter" id="shared_servers"> <h2 id="shared_servers_title">Shared Servers</h2> <p>PHP has shared servers to thank for its popularity. It is hard to find a host without PHP installed, but be sure it’s the latest version. Shared servers allow you and other developers to deploy websites to a single machine. The upside to this is that it has become a cheap commodity. The downside is that you never know what kind of a ruckus your neighboring tenants are going to create; loading down the server or opening up security holes are the main concerns. If your project’s budget can afford to avoid shared servers, you should.</p> <p>Make sure your shared servers are offering the latest versions of PHP.</p> </section> <section class="chapter" id="building_and_deploying_your_application"> <h2 id="building_and_deploying_your_application_title">Building and Deploying your Application</h2> <p>If you find yourself doing manual database schema changes or running your tests manually before updating your files (manually), think twice! With every additional manual task needed to deploy a new version of your app, the chances for potentially fatal mistakes increase. Whether you’re dealing with a simple update, a comprehensive build process or even a continuous integration strategy, <a href="https://wikipedia.org/wiki/Build_automation">build automation</a> is your friend.</p> <p>Among the tasks you might want to automate are:</p> <ul> <li>Dependency management</li> <li>Compilation, minification of your assets</li> <li>Running tests</li> <li>Creation of documentation</li> <li>Packaging</li> <li>Deployment</li> </ul> <h3 id="deployment-tools">Deployment Tools</h3> <p>Deployment tools can be described as a collection of scripts that handle common tasks of software deployment. The deployment tool is not a part of your software, it acts on your software from ‘outside’.</p> <p>There are many open source tools available to help you with build automation and deployment, some are written in PHP others aren’t. This shouldn’t hold you back from using them, if they’re better suited for the specific job. Here are a few examples:</p> <p><a href="https://www.phing.info/">Phing</a> can control your packaging, deployment or testing process from within a XML build file. Phing (which is based on <a href="https://ant.apache.org/">Apache Ant</a>) 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).</p> <p><a href="https://capistranorb.com/">Capistrano</a> is a system for <em>intermediate-to-advanced programmers</em> 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.</p> <p><a href="https://ansistrano.com">Ansistrano</a> 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 <a href="https://capistranorb.com/">Capistrano</a>. It’s been used by quite a lot of PHP companies already.</p> <p><a href="https://deployer.org/">Deployer</a> is a deployment tool written in PHP. It’s simple and functional. Features include running tasks in parallel, atomic deployment and keeping consistency between servers. Recipes of common tasks for Symfony, Laravel, Zend Framework and Yii are available. Younes Rafie’s article <a href="https://www.sitepoint.com/deploying-php-applications-with-deployer/">Easy Deployment of PHP Applications with Deployer</a> is a great tutorial for deploying your application with the tool.</p> <p><a href="https://www.magephp.com/">Magallanes</a> is another tool written in PHP with simple configuration done in YAML files. It has support for multiple servers and environments, atomic deployment, and has some built in tasks that you can leverage for common tools and frameworks.</p> <h4 id="further-reading">Further reading:</h4> <ul> <li><a href="https://code.tutsplus.com/tutorials/automate-your-projects-with-apache-ant--net-18595">Automate your project with Apache Ant</a></li> <li><a href="https://deployingphpapplications.com/">Deploying PHP Applications</a> - paid book on best practices and tools for PHP deployment.</li> </ul> <h3 id="server-provisioning">Server Provisioning</h3> <p>Managing and configuring servers can be a daunting task when faced with many servers. There are tools for dealing with this so you can automate your infrastructure to make sure you have the right servers and that they’re configured properly. They often integrate with the larger cloud hosting providers (Amazon Web Services, Heroku, DigitalOcean, etc) for managing instances, which makes scaling an application a lot easier.</p> <p><a href="https://www.ansible.com/">Ansible</a> 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.</p> <p><a href="https://puppet.com/">Puppet</a> 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 themselves if necessary. In the master-less mode you can push changes to your nodes.</p> <p><a href="https://www.chef.io/">Chef</a> 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.</p> <h4 id="further-reading-1">Further reading:</h4> <ul> <li><a href="https://serversforhackers.com/an-ansible-tutorial">An Ansible Tutorial</a></li> <li><a href="https://leanpub.com/ansible-for-devops">Ansible for DevOps</a> - paid book on everything Ansible</li> <li><a href="https://leanpub.com/ansible-for-aws">Ansible for AWS</a> - paid book on integrating Ansible and Amazon Web Services</li> <li><a href="https://web.archive.org/web/20190307220000/http://www.jasongrimes.org/2012/06/managing-lamp-environments-with-chef-vagrant-and-ec2-1-of-3/">Three part blog series about deploying a LAMP application with Chef, Vagrant, and EC2</a></li> <li><a href="https://github.com/sous-chefs/php">Chef Cookbook which installs and configures PHP and the PEAR package management system</a></li> <li><a href="https://www.youtube.com/playlist?list=PL11cZfNdwNyNYcpntVe6js-prb80LBZuc">Chef video tutorial series</a></li> </ul> <h3 id="continuous-integration">Continuous Integration</h3> <blockquote> <p>Continuous Integration is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily — leading to multiple integrations per day. Many teams find that this approach leads to significantly reduced integration problems and allows a team to develop cohesive software more rapidly.</p> </blockquote> <p><em>– Martin Fowler</em></p> <p>There are different ways to implement continuous integration for PHP. <a href="https://www.travis-ci.com/">Travis CI</a> has done a great job of making continuous integration a reality even for small projects. Travis CI is a hosted continuous integration service. It can be integrated with GitHub and offers support for many languages including PHP. GitHub has continuous integration workflows with <a href="https://docs.github.com/en/actions">GitHub Actions</a>.</p> <h4 id="further-reading-2">Further reading:</h4> <ul> <li><a href="https://jenkins.io/">Continuous Integration with Jenkins</a></li> <li><a href="https://github.com/dancryer/phpci">Continuous Integration with PHPCI</a></li> <li><a href="https://github.com/php-censor/php-censor">Continuous Integration with PHP Censor</a></li> <li><a href="https://www.jetbrains.com/teamcity/">Continuous Integration with Teamcity</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="virtualization"> <h1 id="virtualization_title">Virtualization</h1> <p>Running your application on different environments in development and production can lead to strange bugs popping up when you go live. It’s also tricky to keep different development environments up to date with the same version for all libraries used when working with a team of developers.</p> <p>If you are developing on Windows and deploying to Linux (or anything non-Windows) or are developing in a team, you should consider using a virtual machine. This sounds tricky, but besides the widely known virtualization environments like VMware or VirtualBox, there are additional tools that may help you setting up a virtual environment in a few easy steps.</p> </section> <section class="chapter" id="vagrant"> <h2 id="vagrant_title">Vagrant</h2> <p><a href="https://www.vagrantup.com/">Vagrant</a> helps you build your virtual boxes on top of the known virtual environments and will configure these environments based on a single configuration file. These boxes can be set up manually, or you can use “provisioning” software such as <a href="https://puppet.com/">Puppet</a> or <a href="https://www.chef.io/">Chef</a> to do this for you. Provisioning the base box is a great way to ensure that multiple boxes are set up in an identical fashion and removes the need for you to maintain complicated “set up” command lists. You can also “destroy” your base box and recreate it without many manual steps, making it easy to create a “fresh” installation.</p> <p>Vagrant creates folders for sharing your code between your host and your virtual machine, which means that you can create and edit your files on your host machine and then run the code inside your virtual machine.</p> </section> <section class="chapter" id="docker"> <h2 id="docker_title">Docker</h2> <p><a href="https://www.docker.com/">Docker</a> - a lightweight alternative to a full virtual machine - is so called because it’s all about “containers”. A container is a building block which, in the simplest case, does one specific job, e.g. running a web server. An “image” is the package you use to build the container - Docker has a repository full of them.</p> <p>A typical LAMP application might have three containers: a web server, a PHP-FPM process and MySQL. As with shared folders in Vagrant, you can leave your application files where they are and tell Docker where to find them.</p> <p>You can generate containers from the command line (see example below) or, for ease of maintenance, build a <code class="language-plaintext highlighter-rouge">docker-compose.yml</code> file for your project specifying which to create and how they communicate with one another.</p> <p>Docker may help if you’re developing multiple websites and want the separation that comes from installing each on its 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.</p> <h3 id="example-running-your-php-applications-in-docker">Example: Running your PHP Applications in Docker</h3> <p>After <a href="https://docs.docker.com/get-docker/">installing docker</a> on your machine, you can start a web server with one command. The following will download a fully functional Apache installation with the latest PHP version, map <code class="language-plaintext highlighter-rouge">/path/to/your/php/files</code> to the document root, which you can view at <code class="language-plaintext highlighter-rouge">http://localhost:8080</code>:</p> <figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="go">docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache</span></code></pre></figure> <p>This will initialize and launch your container. <code class="language-plaintext highlighter-rouge">-d</code> makes it run in the background. To stop and start it, simply run <code class="language-plaintext highlighter-rouge">docker stop my-php-webserver</code> and <code class="language-plaintext highlighter-rouge">docker start my-php-webserver</code> (the other parameters are not needed again).</p> <h3 id="learn-more-about-docker">Learn more about Docker</h3> <p>The command above shows a quick way to run a basic server. There’s much more you can do (and thousands of pre-built images in the <a href="https://hub.docker.com/">Docker Hub</a>). Take time to learn the terminology and read the <a href="https://docs.docker.com/">Docker User Guide</a> to get the most from it, and don’t run random code you’ve downloaded without checking it’s safe – unofficial images may not have the latest security patches. If in doubt, stick to the <a href="https://hub.docker.com/explore/">official repositiories</a>.</p> <p>The <a href="https://phpdocker.io/">PHPDocker.io</a> site will auto-generate all the files you need for a fully-featured LAMP/LEMP stack, including your choice of PHP version and extensions.</p> <ul> <li><a href="https://www.docker.com/">Docker Website</a></li> <li><a href="https://docs.docker.com/get-docker/">Docker Installation</a></li> <li><a href="https://docs.docker.com/">Docker User Guide</a></li> <li><a href="https://hub.docker.com/">Docker Hub</a></li> <li><a href="https://hub.docker.com/explore/">Docker Hub - official images</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="caching"> <h1 id="caching_title">Caching</h1> <p>PHP is pretty quick by itself, but bottlenecks can arise when you make remote connections, load files, etc. Thankfully, there are various tools available to speed up certain parts of your application, or reduce the number of times these various time-consuming tasks need to run.</p> </section> <section class="chapter" id="opcode_cache"> <h2 id="opcode_cache_title">Opcode Cache</h2> <p>When a PHP file is executed, it must first be compiled into <a href="https://php-legacy-docs.zend.com/manual/php4/en/internals2.opcodes">opcodes</a> (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.</p> <p>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.</p> <p>It’s likely an opcode cache will make a significant speed improvement to your application. Since PHP 5.5 there is one built in - <a href="https://www.php.net/book.opcache">Zend OPcache</a>. Depending on your PHP package/distribution, it’s usually turned on by default - check <a href="https://www.php.net/manual/opcache.configuration.php#ini.opcache.enable">opcache.enable</a> and the output of <code class="language-plaintext highlighter-rouge">phpinfo()</code> to make sure. For earlier versions there’s a PECL extension.</p> <p>Read more about opcode caches:</p> <ul> <li><a href="https://www.php.net/book.opcache">Zend OPcache</a> (bundled with PHP since 5.5)</li> <li>Zend OPcache (formerly known as Zend Optimizer+) is now <a href="https://github.com/zendtech/ZendOptimizerPlus">open source</a></li> <li><a href="https://www.iis.net/downloads/microsoft/wincache-extension">WinCache</a> (extension for MS Windows Server)</li> <li><a href="https://wikipedia.org/wiki/List_of_PHP_accelerators">list of PHP accelerators on Wikipedia</a></li> <li><a href="https://www.php.net/opcache.preloading">PHP Preloading</a> - PHP >= 7.4</li> </ul> </section> <section class="chapter" id="object_caching"> <h2 id="object_caching_title">Object Caching</h2> <p>There are times when it can be beneficial to cache individual objects in your code, such as with data that is expensive to get or database calls where the result is unlikely to change. You can use object caching software to hold these pieces of data in memory for extremely fast access later on. If you save these items to a data store after you retrieve them, then pull them directly from the cache for following requests, you can gain a significant improvement in performance as well as reduce the load on your database servers.</p> <p>Many of the popular bytecode caching solutions let you cache custom data as well, so there’s even more reason to take advantage of them. APCu and WinCache both provide APIs to save data from your PHP code to their memory cache.</p> <p>The most commonly used memory object caching systems are APCu and memcached. APCu is an excellent choice for object caching, it includes a simple API for adding your own data to its memory cache and is very easy to setup and use. The one real limitation of APCu is that it is tied to the server it’s installed on. Memcached on the other hand is installed as a separate service and can be accessed across the network, meaning that you can store objects in a hyper-fast data store in a central location and many different systems can pull from it.</p> <p>Note that whether the cache is shared across PHP processes depends on how PHP is used. When running PHP via PHP-FPM, the cache is shared across all processes of all pools. When running PHP as a (Fast-)CGI application inside your webserver, the cache is not shared, i.e every PHP process will have its own APCu data. When running PHP as a command line, the cache is not shared and will only exist for the duration of the command. So you have to be mindful of your situation and goals. And you might want to consider using memcached instead, as it’s not tied to the PHP processes.</p> <p>In a networked configuration APCu will usually outperform memcached in terms of access speed, but memcached will be able to scale up faster and further. If you do not expect to have multiple servers running your application, or do not need the extra features that memcached offers then APCu is probably your best choice for object caching.</p> <p>Example logic using APCu:</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="c1">// check if there is data saved as 'expensive_data' in cache</span> <span class="nv">$data</span> <span class="o">=</span> <span class="nb">apcu_fetch</span><span class="p">(</span><span class="s1">'expensive_data'</span><span class="p">);</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$data</span> <span class="o">===</span> <span class="kc">false</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// data is not in cache; save result of expensive call for later use</span> <span class="nb">apcu_add</span><span class="p">(</span><span class="s1">'expensive_data'</span><span class="p">,</span> <span class="nv">$data</span> <span class="o">=</span> <span class="nf">get_expensive_data</span><span class="p">());</span> <span class="p">}</span> <span class="nb">print_r</span><span class="p">(</span><span class="nv">$data</span><span class="p">);</span></code></pre></figure> <p>Note that prior to PHP 5.5, there was the APC extension which provided both an object cache and a bytecode cache. The new APCu is a project to bring APC’s object cache to PHP 5.5+, since PHP now has a built-in bytecode cache (OPcache).</p> <h3 id="learn-more-about-popular-object-caching-systems">Learn more about popular object caching systems:</h3> <ul> <li><a href="https://github.com/krakjoe/apcu">APCu</a></li> <li><a href="https://www.php.net/apcu">APCu Documentation</a></li> <li><a href="https://memcached.org/">Memcached</a></li> <li><a href="https://redis.io/">Redis</a></li> <li><a href="https://www.php.net/ref.wincache">WinCache Functions</a></li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="documenting"> <h1 id="documenting_title">Documenting your Code</h1> </section> <section class="chapter" id="phpdoc"> <h2 id="phpdoc_title">PHPDoc</h2> <p>PHPDoc is an informal standard for commenting PHP code. There are a <em>lot</em> of different <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/index.html">tags</a> available. The full list of tags and examples can be found at the <a href="https://docs.phpdoc.org/latest/index.html">PHPDoc manual</a>.</p> <p>Below is an example of how you might document a class with a few methods;</p> <figure class="highlight"><pre><code class="language-php" data-lang="php"><span class="cp"><?php</span> <span class="cd">/** * @author A Name <a.name@example.com> * @link https://www.phpdoc.org/docs/latest/index.html */</span> <span class="kd">class</span> <span class="nc">DateTimeHelper</span> <span class="p">{</span> <span class="cd">/** * @param mixed $anything Anything that we can convert to a \DateTime object * * @throws \InvalidArgumentException * * @return \DateTime */</span> <span class="k">public</span> <span class="k">function</span> <span class="n">dateTimeFromAnything</span><span class="p">(</span><span class="nv">$anything</span><span class="p">)</span> <span class="p">{</span> <span class="nv">$type</span> <span class="o">=</span> <span class="nb">gettype</span><span class="p">(</span><span class="nv">$anything</span><span class="p">);</span> <span class="k">switch</span> <span class="p">(</span><span class="nv">$type</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// Some code that tries to return a \DateTime object</span> <span class="p">}</span> <span class="k">throw</span> <span class="k">new</span> <span class="err">\</span><span class="nf">InvalidArgumentException</span><span class="p">(</span> <span class="s2">"Failed Converting param of type '</span><span class="si">{</span><span class="nv">$type</span><span class="si">}</span><span class="s2">' to DateTime object"</span> <span class="p">);</span> <span class="p">}</span> <span class="cd">/** * @param mixed $date Anything that we can convert to a \DateTime object * * @return void */</span> <span class="k">public</span> <span class="k">function</span> <span class="n">printISO8601Date</span><span class="p">(</span><span class="nv">$date</span><span class="p">)</span> <span class="p">{</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-></span><span class="nf">dateTimeFromAnything</span><span class="p">(</span><span class="nv">$date</span><span class="p">)</span><span class="o">-></span><span class="nf">format</span><span class="p">(</span><span class="s1">'c'</span><span class="p">);</span> <span class="p">}</span> <span class="cd">/** * @param mixed $date Anything that we can convert to a \DateTime object */</span> <span class="k">public</span> <span class="k">function</span> <span class="n">printRFC2822Date</span><span class="p">(</span><span class="nv">$date</span><span class="p">)</span> <span class="p">{</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-></span><span class="nf">dateTimeFromAnything</span><span class="p">(</span><span class="nv">$date</span><span class="p">)</span><span class="o">-></span><span class="nf">format</span><span class="p">(</span><span class="s1">'r'</span><span class="p">);</span> <span class="p">}</span> <span class="p">}</span></code></pre></figure> <p>The documentation for the class as a whole has the <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/author.html">@author</a> tag and a <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/link.html">@link</a> tag. The <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/author.html">@author</a> tag is used to document the author of the code and can be repeated for documenting several authors. The <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/link.html">@link</a> tag is used to link to a website indicating a relationship between the website and the code.</p> <p>Inside the class, the first method has a <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/param.html">@param</a> tag documenting the type, name and description of the parameter being passed to the method. Additionally it has the <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/return.html">@return</a> and <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/throws.html">@throws</a> tags for documenting the return type, and any exceptions that could be thrown respectively.</p> <p>The second and third methods are very similar and have a single <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/param.html">@param</a> tag as did the first method. The important difference between the second and third methods’ doc block is the inclusion/exclusion of the <a href="https://docs.phpdoc.org/latest/guide/references/phpdoc/tags/return.html">@return</a> tag. <code class="language-plaintext highlighter-rouge">@return void</code> explicitly informs us that there is no return; historically omitting the <code class="language-plaintext highlighter-rouge">@return void</code> statement also results in the same (no return) action.</p> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="resources"> <h1 id="resources_title">Resources</h1> </section> <section class="chapter" id="from_the_source"> <h2 id="from_the_source_title">From the Source</h2> <ul> <li><a href="https://www.php.net/">PHP Website</a></li> <li><a href="https://www.php.net/docs.php">PHP Documentation</a></li> </ul> </section> <section class="chapter" id="people_to_follow"> <h2 id="people_to_follow_title">People to Follow</h2> <p>It’s difficult to find interesting and knowledgeable PHP community members when you are first starting out. You can find an abbreviated list of PHP community members to get you started at:</p> <ul> <li><a href="https://www.ogprogrammer.com/2017/06/28/how-to-get-connected-with-the-php-community/">https://www.ogprogrammer.com/2017/06/28/how-to-get-connected-with-the-php-community/</a></li> <li><a href="https://twitter.com/CalEvans/lists/phpeople">https://twitter.com/CalEvans/lists/phpeople</a></li> </ul> </section> <section class="chapter" id="php_paas_providers"> <h2 id="php_paas_providers_title">PHP PaaS Providers</h2> <ul> <li><a href="https://www.amezmo.com">Amezmo</a></li> <li><a href="https://aws.amazon.com/elasticbeanstalk/">AWS Elastic Beanstalk</a></li> <li><a href="https://www.cloudways.com/">Cloudways</a></li> <li><a href="https://www.digitalocean.com/products/app-platform">DigitalOcean App Platform</a></li> <li><a href="https://www.divio.com/">Divio</a></li> <li><a href="https://www.engineyard.com/">Engine Yard Cloud</a></li> <li><a href="https://www.fortrabbit.com/">fortrabbit</a></li> <li><a href="https://cloud.google.com/appengine/docs/php/">Google App Engine</a></li> <li><a href="https://devcenter.heroku.com/categories/php-support">Heroku</a></li> <li><a href="https://cloud.ibm.com/docs/openwhisk?topic=openwhisk-prep#prep_php">IBM Cloud</a></li> <li><a href="https://www.lumen.com/">Lumen</a></li> <li><a href="https://azure.microsoft.com/">Microsoft Azure</a></li> <li><a href="https://network.pivotal.io/">Pivotal Web Services</a></li> <li><a href="https://platform.sh/">Platform.sh</a></li> <li><a href="https://www.openshift.com/">Red Hat OpenShift</a></li> <li><a href="https://www.virtuozzo.com/application-platform-partners/">Virtuozzo</a></li> </ul> </section> <section class="chapter" id="frameworks"> <h2 id="frameworks_title">Frameworks</h2> <p>Rather than re-invent the wheel, many PHP developers use frameworks to build out web applications. Frameworks abstract away many of the low-level concerns and provide helpful, easy-to-use interfaces to complete common tasks.</p> <p>You do not need to use a framework for every project. Sometimes plain PHP is the right way to go, but if you do need a framework then there are three main types available:</p> <ul> <li>Micro Frameworks</li> <li>Full-Stack Frameworks</li> <li>Component Frameworks</li> </ul> <p>Micro-frameworks are essentially a wrapper to route a HTTP request to a callback, controller, method, etc as quickly as possible, and sometimes come with a few extra libraries to assist development such as basic database wrappers and the like. They are prominently used to build remote HTTP services.</p> <p>Many frameworks add a considerable number of features on top of what is available in a micro-framework; these are called Full-Stack Frameworks. These often come bundled with ORMs, Authentication packages, etc.</p> <p>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.</p> </section> <section class="chapter" id="components"> <h2 id="components_title">Components</h2> <p>As mentioned above “Components” are another approach to the common goal of creating, distributing and implementing shared code. Various component repositories exist, the main two of which are:</p> <ul> <li><a href="/#composer_and_packagist">Packagist</a></li> <li><a href="/#pear">PEAR</a></li> </ul> <p>Both of these repositories have command line tools associated with them to help the installation and upgrade processes, and have been explained in more detail in the <a href="/#dependency_management">Dependency Management</a> section.</p> <p>There are also component-based frameworks and component-vendors that offer no framework at all. These projects provide another source of packages which ideally have little to no dependencies on other packages, or specific frameworks.</p> <p>For example, you can use the <a href="https://github.com/fuelphp/validation">FuelPHP Validation package</a>, without needing to use the FuelPHP framework itself.</p> <ul> <li><a href="https://auraphp.com/framework/">Aura</a></li> <li>CakePHP Components <ul> <li><a href="https://github.com/cakephp/collection">Collection</a></li> <li><a href="https://github.com/cakephp/database">Database</a></li> <li><a href="https://github.com/cakephp/datasource">Datasource</a></li> <li><a href="https://github.com/cakephp/event">Event</a></li> <li><a href="https://github.com/cakephp/i18n">I18n</a></li> <li><a href="https://github.com/cakephp/orm">ORM</a></li> </ul> </li> <li><a href="https://github.com/fuelphp">FuelPHP</a></li> <li><a href="https://github.com/hoaproject">Hoa Project</a></li> <li><a href="https://symfony.com/components">Symfony Components</a></li> <li><a href="https://thephpleague.com/">The League of Extraordinary Packages</a></li> <li>Laravel’s Illuminate Components <ul> <li><a href="https://github.com/illuminate/container">IoC Container</a></li> <li><a href="https://github.com/illuminate/database">Eloquent ORM</a></li> <li><a href="https://github.com/illuminate/queue">Queue</a></li> </ul> </li> </ul> <p><em>Laravel’s <a href="https://github.com/illuminate">Illuminate components</a> will become better decoupled from the Laravel framework. For now, only the components best decoupled from the Laravel framework are listed above.</em></p> </section> <section class="chapter" id="other_resources"> <h2 id="other_resources_title">Other Useful Resources</h2> <h3 id="cheatsheets">Cheatsheets</h3> <ul> <li><a href="https://phpcheatsheets.com/">PHP Cheatsheets</a> - for variable comparisons, arithmetics and variable testing in various PHP versions.</li> <li><a href="https://github.com/smknstd/modern-php-cheatsheet">Modern PHP Cheatsheet</a> - documents modern (PHP 7.0+) idioms in a unified document.</li> <li><a href="https://owasp.org/www-project-cheat-sheets/">OWASP Security Cheatsheets</a> - provides a concise collection of high value information on specific application security topics.</li> </ul> <h3 id="more-best-practices">More best practices</h3> <ul> <li><a href="https://phpbestpractices.org/">PHP Best Practices</a></li> <li><a href="https://kinsta.com/blog/php-versions/">Why You Should Be Using Supported PHP Versions</a></li> </ul> <h3 id="news-around-the-php-and-web-development-communities">News around the PHP and web development communities</h3> <p>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:</p> <ul> <li><a href="https://www.phpweekly.com">PHP Weekly</a></li> <li><a href="https://javascriptweekly.com/">JavaScript Weekly</a></li> <li><a href="https://frontendfoc.us/">Frontend Focus</a></li> <li><a href="https://mobiledevweekly.com/">Mobile Web Weekly</a></li> </ul> <p>There are also Weeklies on other platforms you might be interested in; here’s <a href="https://github.com/jondot/awesome-weekly">a list of some</a>.</p> <h3 id="php-universe">PHP universe</h3> <ul> <li><a href="https://blog.phpdeveloper.org/">PHP Developer blog</a></li> </ul> </section> <section class="chapter" id="videos"> <h2 id="videos">Video Tutorials</h2> <h3 id="youtube-channels">YouTube Channels</h3> <ul> <li><a href="https://github.com/ggelashvili/learnphptherightway-outline">Learn PHP The Right Way Series</a></li> <li><a href="https://www.youtube.com/user/phpacademy">PHP Academy</a></li> <li><a href="https://www.youtube.com/user/thenewboston">The New Boston</a></li> <li><a href="https://www.youtube.com/user/businessgeek">Sherif Ramadan</a></li> <li><a href="https://www.youtube.com/user/LevelUpTuts">Level Up Tuts</a></li> </ul> <h3 id="paid-videos">Paid Videos</h3> <ul> <li><a href="https://teamtreehouse.com/library/php-standards-and-best-practices">Standards and Best practices</a></li> <li><a href="https://www.pluralsight.com/search?q=php">PHP Training on Pluralsight</a></li> <li><a href="https://www.linkedin.com/learning/search?trk=lynda_redirect_learning&sortBy=RELEVANCE&softwareNames=PHP">PHP Training on LinkedIn.com</a></li> <li><a href="https://code.tutsplus.com/categories/php/courses">PHP Training on Tutsplus</a></li> <li><a href="https://laracasts.com/">Laracasts</a></li> <li><a href="https://symfonycasts.com/">SymfonyCasts</a></li> </ul> </section> <section class="chapter" id="books"> <h2 id="books_title">Books</h2> <p>There are many PHP books; sadly some are now quite old and no longer accurate. In particular, avoid books on “PHP 6”, a version that will now never exist. The next major release of PHP after 5.6 was “PHP 7”, <a href="https://wiki.php.net/rfc/php6">partly because of this</a>.</p> <p>This section aims to be a living document for recommended books on PHP development in general. If you would like your book to be added, send a PR and it will be reviewed for relevancy.</p> <h3 id="free-books">Free Books</h3> <ul> <li><a href="https://daylerees.com/php-pandas/">PHP Pandas</a> - Aims to teach everyone how to be a web developer.</li> <li><a href="https://leanpub.com/phptherightway/">PHP The Right Way</a> - This website is available as a book completely for free.</li> <li><a href="https://paragonie.com/book/pecl-libsodium">Using Libsodium in PHP Projects</a> - Guide to using Libsodium PHP extension for modern, secure, and fast cryptography.</li> </ul> <h3 id="paid-books">Paid Books</h3> <ul> <li><a href="https://phpandmysql.com/">PHP & MySQL</a> - PHP book with excellent illustrations that covers all the fundamentals of PHP and MySQL with practical examples.</li> <li><a href="https://apisyouwonthate.com/">Build APIs You Won’t Hate</a> - Everyone and their dog wants an API, so you should probably learn how to build them.</li> <li><a href="https://www.oreilly.com/library/view/modern-php/9781491905173/">Modern PHP</a> - Covers modern PHP features, best practices, testing, tuning, deployment and setting up a dev environment.</li> <li><a href="https://leanpub.com/buildingsecurephpapps">Building Secure PHP Apps</a> - Learn the security basics that a senior developer usually acquires over years of experience, all condensed down into one quick and easy handbook.</li> <li><a href="https://leanpub.com/mlaphp">Modernizing Legacy Applications In PHP</a> - Get your code under control in a series of small, specific steps.</li> <li><a href="https://leanpub.com/securingphp-coreconcepts">Securing PHP: Core Concepts</a> - A guide to some of the most common security terms and provides some examples of them in every day PHP.</li> <li><a href="https://www.scalingphpbook.com/">Scaling PHP</a> - Stop playing sysadmin and get back to coding.</li> <li><a href="https://leanpub.com/signalingphp">Signaling PHP</a> - PCNLT signals are a great help when writing PHP scripts that run from the command line.</li> <li><a href="https://leanpub.com/minimumviabletests">Minimum Viable Tests</a> - Long-time PHP testing evangelist Chris Hartjes goes over what he feels is the minimum you need to know to get started.</li> <li><a href="https://leanpub.com/ddd-in-php">Domain-Driven Design in PHP</a> - 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.</li> </ul> </section> <div class="back-to-top"><p><a href="#top" class="top">Back to Top</a></p> </div> <section class="chapter" id="community"> <h1 id="community_title">Community</h1> <p>The PHP community is as diverse as it is large, and its members are ready and willing to support new PHP programmers. Consider joining your local PHP user group (PUG) or attending larger PHP conferences to learn more about the best practices shown here. You can hang out on IRC in the #phpc channel on <a href="https://webchat.freenode.net/?channels=phpc">irc.freenode.com</a> and follow the @phpc on <a href="https://twitter.com/phpc">Twitter</a> or <a href="https://phpc.social/">Mastodon</a>. Get out there, meet new developers, learn new topics, and above all, make new friends! Other community resources include <a href="https://stackoverflow.com/questions/tagged/php">StackOverflow</a>.</p> <p><a href="https://www.php.net/cal.php">Read the Official PHP Events Calendar</a></p> </section> <section class="chapter" id="user_groups"> <h2 id="user_groups_title">PHP User Groups</h2> <p>If you live in a larger city, odds are there’s a PHP user group nearby. You can easily find your local PUG at <a href="https://php.ug/">PHP.ug</a>. Alternate sources might be <a href="https://www.meetup.com/find/">Meetup.com</a> or a search for <code class="language-plaintext highlighter-rouge">php user group near me</code> using your favorite search engine (i.e. <a href="https://www.google.com/search?q=php+user+group+near+me">Google</a>). If you live in a smaller town, there may not be a local PUG; if that’s the case, start one!</p> <p>Special mention should be made of two global user groups: <a href="https://nomadphp.com/">NomadPHP</a> and <a href="https://twitter.com/PHPWomen">PHPWomen</a>. <a href="https://nomadphp.com/">NomadPHP</a> offers twice monthly online user group meetings with presentations by some of the top speakers in the PHP community. <a href="https://twitter.com/PHPWomen">PHPWomen</a> is a non-exclusive user group originally targeted towards the women in the PHP world. Membership is open to everyone who supports a more diverse community. PHPWomen provide a network for support, mentorship and education, and generally promote the creating of a “female friendly” and professional atmosphere.</p> <p><a href="https://wiki.php.net/usergroups">Read about User Groups on the PHP Wiki</a></p> </section> <section class="chapter" id="conferences"> <h2 id="conferences_title">PHP Conferences</h2> <p>The PHP community also hosts larger regional and national conferences in many countries around the world. Well-known members of the PHP community usually speak at these larger events, so it’s a great opportunity to learn directly from industry leaders.</p> <p><a href="https://www.php.net/conferences/index.php">Find a PHP Conference</a></p> </section> <section class="chapter" id="elephpants"> <h2 id="elephpants_title">ElePHPants</h2> <p><a href="https://www.php.net/elephpant.php">ElePHPant</a> is that beautiful mascot of the PHP project with an elephant in its design. It was originally designed for the PHP project in 1998 by <a href="http://www.elroubio.net/">Vincent Pontier</a> - spiritual father of thousands of elePHPants around the world - and ten years later adorable plush elephant toys came to birth as well. Now elePHPants are present at many PHP conferences and with many PHP developers at their computers for fun and inspiration.</p> <p><a href="https://7php.com/elephpant/">Interview with Vincent Pontier</a></p> </section> </div> <footer class="site-footer" id="credits"> <h2>Created and maintained by</h2> <ul> <li><a href="https://joshlockhart.com" target="_blank">Josh Lockhart</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> </ul> <div class="license"> <a class="cc-badge" rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/"></a> <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="https://joshlockhart.com" property="cc:attributionName" rel="cc:attributionURL">Josh Lockhart</a> <br/> 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> </footer> </body> </html>