Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Writing Effective PHP @ Forum PHP 2019

Writing Effective PHP @ Forum PHP 2019

PHP has evolved massively since its first days, and it's on the road to a full-featured language. However, at the same time, there is a lot of outdated information and libraries with poorly written code.

This talk is about writing PHP Code that is: safe, robust, and maintainable. We are going to cover a set of rules, that if you follow them; they will get you on the habit of writing code well.

Get ready for a 25 min live-coding session, where I go through practical examples. You will learn how to design classes, how to think about your API to prevent breaking changes, and discover concepts around designing and creating objects, when and how to use immutability, and much more.

Nuno Maduro

October 24, 2019
Tweet

More Decks by Nuno Maduro

Other Decks in Programming

Transcript

  1. HOW WRITE IMMUTABLE CLASSES? ▸ Constructor is the only Injection

    Point ▸ No setters ▸ Private Attributes ▸ Make state private
  2. WHEN TO ASSERT INPUT? ▸ Always ▸ Build your own

    helpers to avoid code duplication ▸ Consider the package "beberlei/assert"
  3. final class Money { /** * I know this sucks!

    But I have deployed * this in a rush last friday ahahah. Good Luck! */ public function __construct(int $amount); }
  4. /** * Takes the `amount` of the instance attribute `$money`

    to create {...} using * the instance attribute `$dataTime` for the field `created_at`. * * @throws \Domain\Exceptions\SomethingNotAvailable If something is not available. */ public function handle(): void
  5. HOW WRITE A SOLID CONTRACT? ▸ What is it ▸

    What it does ▸ What it returns ▸ What is the behavior ▸ What is the behavior when the contract gets violated
  6. class Db { /* ... */ } class Core extends

    Db { /* ... */ } class User extends Core { /* ... */ } class Admin extends User { /* ... */ } class Bot extends Admin { /* ... */ } class BotThatDoesSpecialThings extends Bot { /* ... */ } class PatchedBot extends BotThatDoesSpecialThings { /* ... */ } class PatchedBotVersion2019 extends PatchedBot { /* ... */ }
  7. class Food {} class Human extends Food {} class Nuno

    extends Human {} $nuno = new Nuno(); $nuno->eat();
  8. COMPOSITION OVER INHERITANCE final class Food {} $food = new

    Food(); $nuno = new Nuno() $nuno->eat($food);
  9. HOW HAVE HIGH QUALITY TESTS? ▸ Add 100% of real

    Test Coverage - PHPUnit ▸ Use and abuse Static Analysis - PHPStan & PHP Insights
  10. PLEASE CONSIDER THIS PRACTICES ▸ Open Source Libraries ▸ Important

    pieces of your software ▸ Long-lived projects