Better PHP Development

It’s a long process that only comes with practice. Once you move beyond asking “How can I solve this?” to “How should I solve this?”.

In general, I’d say applying a couple of principles to your code will demonstrate to you how to code is better. It’s not immediately obvious what advantages they give until you’ve used them in real projects. The benefits come to you when you try to use your code and realise how flexible and easy to maintain it is.

  1. Favour composition over inheritance. I actually removed 99% of “Extends” keywords from my codebase and it became a hundred times better. It wasn’t until I did it that I realised quite how much I was coding to work around inheritance and using it where I really shouldn’t be.

  2. Make all class variables private and avoid getters/setters unless they are absolutely needed. This goes hand in hand with 1) but it will help you achieve better encapsulation, which is a fundamental principle in OOP.

  3. Dependency inejection. Once I started using a dependency injection container, I realised that most of the code I had was messy. Creating objects arbitrarily is messy! Try IoC (inversion of control) and you’ll quickly see the benefits.

  4. Law of demeter: Apply this and your code will become better. It’s not immediately obvious if you don’t understand it, but it forces you to think about the dependencies your classes have.

  5. Unit testing. Once you start writing code that’s easy to test, you have code that’s easy to isolate and therefore, reuse.

That’s my top 5 tips for going from “advanced” to “pro”.