### Install Jekyll and Run Local Server Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/CONTRIBUTING.md Install project dependencies using Bundler and start the local Jekyll development server to preview changes. ```bash bundle install --path vendor/bundle bundle exec jekyll serve ``` -------------------------------- ### Install a PEAR Package Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/04-03-01-PEAR.md Use this command to install a package listed on the PEAR packages list by its official name. ```console pear install foo ``` -------------------------------- ### Start PHP Built-in Web Server Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/01-03-01-Built-in-Web-Server.md Run this command in your terminal from your project's web root to start the server on localhost port 8000. This is useful for quick local testing and development. ```console php -S localhost:8000 ``` -------------------------------- ### Install PHP via Homebrew Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/01-04-01-Mac-Setup.md Use this command to install the latest PHP version using Homebrew. Ensure Homebrew is installed first. ```bash brew install php ``` -------------------------------- ### Install Project Dependencies with Composer Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/04-02-01-Composer-and-Packagist.md Downloads and installs all dependencies defined in composer.json into the vendor/ directory. Use this for projects that already have a composer.json file. ```bash composer install ``` -------------------------------- ### Install Composer Globally Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/04-02-01-Composer-and-Packagist.md Moves the composer.phar binary to /usr/local/bin for global access. Prefix with sudo if permissions are denied. ```bash mv composer.phar /usr/local/bin/composer ``` -------------------------------- ### Install Global PHP Package with Composer Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/04-02-01-Composer-and-Packagist.md Use this command to install a PHP package globally, making its binaries available system-wide. Ensure the Composer vendor bin directory is added to your system's PATH. ```bash composer global require phpunit/phpunit ``` -------------------------------- ### Install Dependencies on Debian Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/01-06-01-Linux-Setup.md Install essential packages like lsb-release, ca-certificates, and curl, which are often required for managing software repositories. ```bash sudo apt-get -y install lsb-release ca-certificates curl ``` -------------------------------- ### PHP Dependency Inversion Example Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/06-03-01-Complex-Problem.md Demonstrates the Dependency Inversion Principle by having a Database class depend on an AdapterInterface rather than a concrete MysqlAdapter. This allows for easier mocking and future database migrations. ```php 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" ``` -------------------------------- ### Gettext Directory Structure Example Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/05-06-01-Internationalization-and-Localization.md Illustrates the standard directory layout for Gettext translation files within a project. This structure helps organize locale-specific message files. ```console ├─ 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/ └─ ... ``` -------------------------------- ### Use a PEAR Package with Composer Autoloader Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/04-03-01-PEAR.md After installing a PEAR package via Composer, include the autoloader and use the package's classes. ```php adapter = new MySqlAdapter; } } class MysqlAdapter {} ``` -------------------------------- ### Configure Locale and Text Domains in PHP Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/05-06-01-Internationalization-and-Localization.md This setup file determines the user's locale based on query parameters, cookies, or browser preferences, and configures Gettext to load translations from specific directories and domains. ```php '_']); }); foreach ($langs as $browser_lang) { if (valid($browser_lang)) { $lang = $browser_lang; break; } } } // here we define the global system locale given the found language putenv("LANG=$lang"); // this might be useful for date functions (LC_TIME) or money formatting (LC_MONETARY), for instance setlocale(LC_ALL, $lang); // this will make Gettext look for ../locales//LC_MESSAGES/main.mo bindtextdomain('main', '../locales'); // indicates in what encoding the file should be read bind_textdomain_codeset('main', 'UTF-8'); // if your application has additional domains, as cited before, you should bind them here as well bindtextdomain('forum', '../locales'); bind_textdomain_codeset('forum', 'UTF-8'); // here we indicate the default domain the gettext() calls will respond to textdomain('main'); // this would look for the string in forum.mo instead of main.mo // echo dgettext('forum', 'Welcome back!'); ?> ``` -------------------------------- ### Switch PHP Versions with Homebrew Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/01-04-01-Mac-Setup.md Manually switch between installed Homebrew PHP versions by unlinking the current version and linking the desired one. This modifies your PATH. ```bash brew unlink php brew link --overwrite php@8.2 ``` ```bash brew unlink php brew link --overwrite php@8.3 ``` -------------------------------- ### Update Package List on Debian Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/01-06-01-Linux-Setup.md Before installing new packages on Debian, update your system's package list to ensure you have the latest information. ```bash sudo apt-get update ``` -------------------------------- ### Update Project Dependencies with Composer Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/04-02-01-Composer-and-Packagist.md Upgrades project dependencies to the newest versions that satisfy the constraints defined in composer.json. Use 'composer install' for deployment. ```bash composer update ``` -------------------------------- ### Full UTF-8 Configuration and Database Interaction in PHP Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/05-05-01-PHP-and-UTF8.md This comprehensive example demonstrates setting internal encoding, default charset, and HTTP output to UTF-8. It includes database interaction using PDO to store and retrieve UTF-8 strings, along with an HTML structure and a helper function for escaping output. ```php PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => false ) ); // Store our transformed string as UTF-8 in our database // Your DB and tables are in the utf8mb4 character set and collation, right? $handle = $link->prepare('insert into ElvishSentences (Id, Body, Priority) values (default, :body, :priority)'); $handle->bindParam(':body', $string, PDO::PARAM_STR); $priority = 45; $handle->bindParam(':priority', $priority, PDO::PARAM_INT); // explicitly tell pdo to expect an int $handle->execute(); // Retrieve the string we just stored to prove it was stored correctly $handle = $link->prepare('select * from ElvishSentences where Id = :id'); $id = 7; $handle->bindParam(':id', $id, PDO::PARAM_INT); $handle->execute(); // Store the result into an object that we'll output later in our HTML // This object won't kill your memory because it fetches the data Just-In-Time to $result = $handle->fetchAll(\PDO::FETCH_OBJ); // An example wrapper to allow you to escape data to html function escape_to_html($dirty){ echo htmlspecialchars($dirty, ENT_QUOTES, 'UTF-8'); } header('Content-Type: text/html; charset=UTF-8'); // Unnecessary if your default_charset is set to utf-8 already ?> UTF-8 test page Body); // This should correctly output our transformed UTF-8 string to the browser } ?> ``` -------------------------------- ### Gettext Plural Form Rules Examples Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/05-06-01-Internationalization-and-Localization.md Demonstrates how to define pluralization rules for different languages within Gettext PO files. These rules determine which plural form of a sentence to use based on a given number. ```po msgid "" msgstr "" "Plural-Forms: nplurals=1; plural=0;\n" ``` ```po msgid "" msgstr "" "Plural-Forms: nplurals=2; plural=(n != 1);\n" ``` ```po msgid "" msgstr "" "Plural-Forms: nplurals=2; plural=(n > 1);\n" ``` -------------------------------- ### Basic Separation: Function for Database Query Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/07-04-01-Interacting-via-Code.md Start separating concerns by encapsulating database queries in functions. This is a foundational step towards better code organization. ```php query('SELECT * FROM table'); } $results = getAllFoos($db); foreach ($results as $row) { echo "
  • " . $row['field1'] . " - " . $row['field1'] . "
  • "; // BAD!! } ?> ``` -------------------------------- ### Run CLI Program with Arguments Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/03-05-01-Command-Line-Interface.md Demonstrates how to execute the 'hello.php' script from the command line, showing both incorrect usage and correct usage with an argument. ```console > php hello.php Usage: php hello.php > php hello.php world Hello, world ``` -------------------------------- ### PHP Strategy Pattern: Runtime Usage Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/pages/Design-Patterns.md Demonstrates how to instantiate and use the client class with different output strategies at runtime. ```php setOutput(new ArrayOutput()); $data = $client->loadOutput(); // Want some JSON? $client->setOutput(new JsonStringOutput()); $data = $client->loadOutput(); ``` -------------------------------- ### Clone and Configure Repository Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/CONTRIBUTING.md Steps to fork the project, clone your fork, and set up the upstream remote for contributing. ```bash git clone https://github.com//php-the-right-way.git cd php-the-right-way git remote add upstream https://github.com/codeguy/php-the-right-way.git ``` -------------------------------- ### MVC Structure: Main Application File Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/07-04-01-Interacting-via-Code.md This file demonstrates how to set up a basic MVC structure by instantiating a model and including a view. It requires a PDO connection and a separate model file. ```php getAllFoos(); // Show the view include 'views/foo-list.php'; ``` -------------------------------- ### Excessively Nested Ternary Operator in PHP Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/pages/The-Basics.md This example demonstrates deeply nested ternary operators, which sacrifice readability and are generally discouraged. ```php php -i ``` -------------------------------- ### Connect to MySQL and SQLite with PDO Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/07-03-01-Databases_PDO.md Demonstrates establishing connections to both MySQL and SQLite databases using the PDO extension. Shows basic query execution and fetching results. ```php query("SELECT some_field FROM some_table"); $row = $statement->fetch(PDO::FETCH_ASSOC); echo htmlentities($row['some_field']); // PDO + SQLite $pdo = new PDO('sqlite:/path/db/foo.sqlite'); $statement = $pdo->query("SELECT some_field FROM some_table"); $row = $statement->fetch(PDO::FETCH_ASSOC); echo htmlentities($row['some_field']); ``` -------------------------------- ### Create a Simple CLI Program Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/03-05-01-Command-Line-Interface.md This PHP script takes a name as a command-line argument and prints a greeting. It checks for the correct number of arguments and exits with an error code if usage is incorrect. ```php " . PHP_EOL; exit(1); } $name = $argv[1]; echo "Hello, $name" . PHP_EOL; ``` -------------------------------- ### Simple Plain PHP Template with Plates Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/08-03-01-Plain-PHP-Templates.md Demonstrates a basic template structure using the Plates library, including inserting headers and footers, and escaping dynamic content. ```php insert('header', ['title' => 'User Profile']) ?>

    User Profile

    Hello, escape($name)?>

    insert('footer') ?> ``` -------------------------------- ### Run PHP Apache Web Server Container Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/13-03-01-Docker.md Use this command to download and run an Apache web server with PHP. It maps local PHP files to the container's document root and exposes the server on a specific port. Run containers in the background with '-d'. ```bash docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache ``` -------------------------------- ### Basic Twig Template Inclusion Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/08-04-01-Compiled-Templates.md Demonstrates how to include other templates and pass variables in Twig. Ensure the 'header.html' and 'footer.html' templates exist in the appropriate directory. ```html+jinja {% include 'header.html' with {'title': 'User Profile'} %}

    User Profile

    Hello, {{ name }}

    {% include 'footer.html' %} ``` -------------------------------- ### Update Package List on Ubuntu Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/01-06-01-Linux-Setup.md After adding a PPA, update your system's package list to fetch information about the newly available packages. ```bash sudo apt update ``` -------------------------------- ### Add PHP Repository to Debian Sources Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/01-06-01-Linux-Setup.md Add the PHP repository to your system's sources list, ensuring it's signed with the downloaded key. This command dynamically includes your distribution's codename. ```bash sudo sh -c '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' ``` -------------------------------- ### Download Repository Signing Key for Debian Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/01-06-01-Linux-Setup.md Download the GPG key used to sign the PHP packages from Ondřej Surý's repository. This is crucial for verifying package integrity. ```bash sudo curl -sSLo /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg ``` -------------------------------- ### Add Ondřej Surý PPA to Ubuntu Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/01-06-01-Linux-Setup.md Use this command to add the PPA to your Ubuntu system's software sources. This allows access to newer PHP versions. ```bash sudo add-apt-repository ppa:ondrej/php ``` -------------------------------- ### MVC Structure: View File Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/07-04-01-Interacting-via-Code.md The 'foo-list.php' view file handles the presentation logic, iterating over the data provided by the model to display list items. ```php
  • -
  • ``` -------------------------------- ### Create a New Topic Branch Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/CONTRIBUTING.md Create a new branch for your changes, branching off the main project development branch. ```bash git checkout -b ``` -------------------------------- ### Configure Composer for PEAR Packages Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/04-03-01-PEAR.md Manually add a repository to Composer to handle PEAR dependencies, especially for Composer version 2 and later. ```json { "repositories": [ { "type": "package", "package": { "name": "pear2/pear2-http-request", "version": "2.5.1", "dist": { "url": "https://github.com/pear2/HTTP_Request/archive/refs/heads/master.zip", "type": "zip" } } } ], "require": { "pear2/pear2-http-request": "*" }, "autoload": { "psr-4": {"PEAR2\\HTTP\\": "vendor/pear2/pear2-http-request/src/HTTP/" } } ``` -------------------------------- ### Plain PHP Template Inheritance with Plates Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/08-03-01-Plain-PHP-Templates.md Illustrates template inheritance using the Plates library. A base template defines the structure, and a child template extends it, filling in specific content sections. ```php <?=$title?>
    section('content')?>
    ``` ```php layout('template', ['title' => 'User Profile']) ?>

    User Profile

    Hello, escape($name)?>

    ``` -------------------------------- ### Create and Format DateTime Objects Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/05-03-01-Date-and-Time.md Convert a date string to a DateTime object and format it for output. Use `createFromFormat()` for specific string formats and `format()` to display the date. ```php format('Y-m-d') . PHP_EOL; ``` -------------------------------- ### Create Objects with Factory Pattern in PHP Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/pages/Design-Patterns.md Use this pattern to abstract object creation. It centralizes changes to object instantiation, simplifying maintenance and managing complex object creation logic. ```php vehicleMake = $make; $this->vehicleModel = $model; } public function getMakeAndModel() { return $this->vehicleMake . ' ' . $this->vehicleModel; } } class AutomobileFactory { public static function create($make, $model) { return new Automobile($make, $model); } } // have the factory create the Automobile object $veyron = AutomobileFactory::create('Bugatti', 'Veyron'); print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron" ?> ``` -------------------------------- ### Configure Development Error Reporting Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/10-07-01-Error-Reporting.md Use these settings in `php.ini` for development to display all errors. Passing `-1` or `E_ALL` (since PHP 5.4) reports every possible error. ```ini display_errors = On display_startup_errors = On error_reporting = -1 log_errors = On ``` -------------------------------- ### Hash and Verify Password in PHP Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/10-03-01-Password-Hashing.md Use `password_hash()` to create a secure hash of a password and `password_verify()` to check if a given password matches the hash. `password_hash()` handles salting automatically, storing it within the hash itself. ```php * @link https://docs.phpdoc.org/ */ class DateTimeHelper { /** * @param mixed $anything Anything that we can convert to a \DateTime object * * @throws \InvalidArgumentException * * @return \DateTime */ public function dateTimeFromAnything($anything) { $type = gettype($anything); switch ($type) { // Some code that tries to return a \DateTime object } throw new \InvalidArgumentException( "Failed Converting param of type '{$type}' to DateTime object" ); } /** * @param mixed $date Anything that we can convert to a \DateTime object * * @return void */ public function printISO8601Date($date) { echo $this->dateTimeFromAnything($date)->format('c'); } /** * @param mixed $date Anything that we can convert to a \DateTime object */ public function printRFC2822Date($date) { echo $this->dateTimeFromAnything($date)->format('r'); } } ``` -------------------------------- ### PHP Strategy Pattern: Client Class Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/pages/Design-Patterns.md A client class that uses a strategy pattern, allowing the output behavior to be set at runtime via type hinting. ```php output = $outputType; } public function loadOutput() { return $this->output->load(); } } ``` -------------------------------- ### PHP Strategy Pattern: Output Interfaces Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/pages/Design-Patterns.md Defines a common interface for different output algorithms. New output types can be added without affecting client code. ```php ``` -------------------------------- ### PHP Switch Statement Behavior Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/pages/The-Basics.md Illustrates the behavior of PHP switch statements, including value comparison (not type), sequential case execution without 'break', and the effect of 'return' within a function. Use 'break' to exit the switch or 'return' to exit the function. ```php db->query('SELECT * FROM table'); } } ``` -------------------------------- ### Creating Filter Functions with Closures in PHP Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/pages/Functional-Programming.md Illustrates how to create a factory function that returns a closure. This closure captures a variable from its outer scope, enabling the creation of specialized filter functions dynamically for use with array_filter. ```php $min * * Returns a single filter out of a family of "greater than n" filters */ function criteria_greater_than($min) { return function($item) use ($min) { return $item > $min; }; } $input = array(1, 2, 3, 4, 5, 6); // Use array_filter on a input with a selected filter function $output = array_filter($input, criteria_greater_than(3)); print_r($output); // items > 3 ?> ``` -------------------------------- ### PHP Strict vs. Loose Comparison Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/pages/The-Basics.md Demonstrates the difference between strict (===) and loose (==) comparison operators in PHP, highlighting how type juggling can affect outcomes. Use strict comparison when type and value must match. ```php prepare('SELECT name FROM users WHERE id = :id'); $id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); // <-- filter your data first (see [Data Filtering](#data_filtering)), especially important for INSERT, UPDATE, etc. $stmt->bindParam(':id', $id, PDO::PARAM_INT); // <-- Automatically sanitized for SQL by PDO $stmt->execute(); ``` -------------------------------- ### PHP Notice: Undefined Variable Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/_posts/09-02-01-Errors.md Demonstrates a common PHP notice for an undefined variable, which does not halt script execution. ```console $ php -a php > echo $foo; Notice: Undefined variable: foo in php shell code on line 1 ``` -------------------------------- ### PHP String Concatenation Best Practices Source: https://github.com/codeguy/php-the-right-way/blob/gh-pages/pages/The-Basics.md Demonstrates preferred methods for string concatenation in PHP, favoring the concatenation operator (.) over the concatenating assignment operator (.=) for readability, especially on multi-line strings. Indent new lines for clarity. ```php