Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Nikola Poša:
Using DIC the right way
Sep 05, 2017 @ 10:24:31

In a new post to his site Nikola Poša looks at dependency injection containers and shares what he thinks is the right way to use them in your applications.

DIC stands for Dependency Injection Container, which is a tool that manages the construction and wiring up of application services. It closely relates to the letter "D" of a SOLID acronym - Dependency Inversion Principle and is employed to facilitate adhering to the principle.

By their nature, DI Containers are also Service Locator implementations, design pattern that is the exact opposite to Dependency Injection. Because of that, DI Container is a double-edged sword which can mislead you if not used wisely, and ironically bring your code into a state in which there is no dependency injection at all.

He starts off by talking about two kinds of code in an application: core versus assembly. In this case "core" code is the piece of the application that are then used by "assembly" code to make things happen. He suggests that the DIC shouldn't leak into the core and should be put behind a separation between the core code and assembly code. He includes some sample code illustrating what he means and the idea of splitting out the DIC configuration to help that layer clean.

tagged: dependency injection container tutorial core assembly code abstraction leak

Link: http://blog.nikolaposa.in.rs/2017/09/03/using-dic-the-right-way/

Jon LeMaitre:
Separation of Concerns with Laravel’s Eloquent (Series)
Nov 10, 2015 @ 09:10:47

Jon LeMaitre has written up a series of posts talking about effective separation of concerns using Eloquent, the database access component of the Laravel framework. His goal is to show you how makes use of the library and keep your application both maintainable and readable.

Eloquent (and by extension, Laravel) is often criticized because of its ActiveRecord ORM implementation, and that DataMapper produces a cleaner, more maintainable architecture in the long run. [...] This combination of behaviors crammed into a single object in itself is not the problem (in fact, it’s a wonderful asset), the problem is in how you make use of those behaviors throughout your application. You can be sloppy with them, or you can be tidy with them.

He starts with the "sloppy approach" where different methods of accessing the objects (and their data) are spread all across the application. He counters this with the tidy approach that makes use of "persistence-agnostic 'POPOs'" to hide the logic behind repositories. In the second part of the series he starts in and puts this idea into practice, using a simple "Member" table and model and repository classes to abstract the logic. Finally, in part three he gets into some more extended functionality for the repositories approach: handling collections, relations, eager loading and schema changes.

tagged: laravel eloquent designpattern repository orm datamapper activerecord abstraction tutorial series

Link: https://medium.com/laravel-news/separation-of-concerns-with-laravel-s-eloquent-part-1-an-introduction-c9a6dc6b4a65#.o0qsccqos

Hannes Van De Vreken:
Why You Should Avoid Over-Abstracting
Sep 29, 2015 @ 09:35:24

Hannes Van De Vreken has some advice for the PHP developers out there working on projects that make use of some form of abstraction - don't over-abstract. In his case, he's talking more about the use of abstract classes and where they fit into a good overall project structure.

Some time ago I started working on an existing project, so I read the documentation before diving in. At the top of the contributing.md file there was this sentence: “Abstract when possible”. Quickly I learned the project contained more abstract classes than a normal project. This leads to too highly coupled, and often unchangeable code.

This post is dedicated on explaining why “abstract when possible” isn’t good advice. Not only in PHP, but in all programming languages.

He starts with some of the common issues he sees with abstract classes including the over-complication of abstract methods and defining all dependencies the children need even though the abstract class doesn't. To help resolve these issues he recommends the use of traits. These traits include the dependencies needed by the child classes (for example only things needed for a CSV export, not other types). He includes all the code for this particular example. Finally he looks at situations where abstract classes are okay to use. He uses the LeagueEvent package as an example, showing how it creates a listener interface and an abstract class that contains an equality check function. He shows how to refactor this as a trait too.

tagged: abstraction overuse trait tutorial leagueevent example

Link: http://blog.madewithlove.be/post/on-over-abstracting/

Ross Tuck:
How I Use Traits
May 18, 2015 @ 12:56:47

Ross Tuck has posted a new article to his site today talking about how he uses traits in his applications and where he sees them having the most value.

Recently, a few folks asked about a trait in a new project I wrote. Right around the same time, Rafael Dohms showed me his new talk about complex cognitive processes we don’t notice. Because my brain is a big mushy sack, the two blended together. The result was this post, which tries to capture how I use traits but also how I decide to use them in the first place.

He starts off with a bit of talk about leverage versus abstraction and how the concepts relate to code. He includes a brief example of each and points out that, while each is good, abstraction tends to be more useful. He then applies this back to the world of traits, how they compare to the use of normal static methods and how they have an advantage of encapsulation without oversharing. He suggests that assertions are more fit as static methods and that traits are a better fit in cases where multiple inheritance is needed. He also touches in interfaces in traits and his opinion on when is the best time to use them.

tagged: using traits opinion leverage abstraction static interface inheritance

Link: http://rosstuck.com/how-i-use-traits/

Symfony Blog:
New in Symfony 2.7: Twig as a First-Class Citizen
Jan 15, 2015 @ 13:16:18

The Symfony blog has a new post about a change coming in the next version of the popular PHP framework - treating Twig as a first-class citizen. This update removes the abstraction layer that was introduced for it to be used in templating.

When I started to work on Symfony2, Twig didn't exist. Anyway, to ease using PHP as a templating engine, I created the Symfony Templating Component. Later on, not very satisfied with using PHP as a templating language, I decided to create a new templating language, Twig, based on the Python Jinja2 language. And Symfony2 became the first popular framework to adopt a non-PHP templating engine in core. [...] But what would Twig as a First-Class Citizen mean in Symfony2 then? To be able to support PHP and Twig in Symfony, we added an abstraction layer. [...] For Symfony 3.0, I'd like to extract the Templating Component into an independent library (for the few people using PHP with Symfony) but I'd also like for Twig to be front and center in the framework. The good news is that most of the work has already been done in Symfony 2.7.

He compares the two methods for using Twig, one in 2.6 and the other in 2.7, showing both the reduction in code needed and the overall speed improvement gained by removing the excess layer. He includes a link to the Blackfire.io reports showing the difference in the metrics with a total of 48 classes less to load just by removing this layer.

tagged: symfony twig firstclass citizen templating abstraction performance

Link: http://symfony.com/blog/new-in-symfony-2-7-twig-as-a-first-class-citizen

Matthew Weier O'Phinney:
On HTTP, Middleware, and PSR-7
Jan 09, 2015 @ 11:38:17

Matthew Weier O'Phinney has a new post to his site today with a thought about how to make the Zend Framework (both ZF1 & ZF2) easier for developers to get into and use. He suggests that middleware might be the answer.

As I've surveyed the successes and failures of ZF1 and ZF2, I've started considering how we can address usability: how do we make the framework more approachable? One concept I've been researching a ton lately is middleware. Middleware exists in a mature form in Ruby (via Rack), Python (via WSGI), and Node (via Connect / ExpressJS); just about every language has some exemplar. Even PHP has some examples already, in StackPHP and Slim Framework.

[...] The idea is that objects, hashes, or structs representing the HTTP request and HTTP response are passed to a callable, which does something with them. You compose these in a number of ways to build an application.

He gives some examples of current frameworks and libraries that make use of the middleware idea, showing both object and callable methods. He points out that, while middleware is approachable and makes a developer's life easier, it's not something PHP can internally handle. He covers the things a PHP developer would need to access just to get the complete details about a HTTP request and that what's really needed is good HTTP abstraction handling, something the PHP-FIG group has been working on as a part of PSR-7. He includes some examples of how it might be used and where middleware would fit into the picture.

Too often, I feel as PHP developers we focus on the tools we use, and forget that we're working in an HTTP-centric ecosystem. [...] If PSR-7 is ratified, I think we have a strong foot forward towards building framework-agnostic web-focused components that have real re-use capabilities -- not just re-use within our chosen framework fiefdoms.
tagged: middleware http psr7 abstraction language handling

Link: https://mwop.net/blog/2015-01-08-on-http-middleware-and-psr-7.html

Anthony Ferrara:
A Beginner's Guide To MVC For The Web
Nov 24, 2014 @ 10:42:41

Anthony Ferrara has posted what he calls a beginners guide to MVC for the web, a tutorial that introduces to you the basic concepts behind the Model-View-Controller design pattern and how it should fit in with the SOLID design principles.

There are a bunch of guides out there that claim to be a guide to MVC. It's almost like writing your own framework in that it's "one of those things" that everyone does. I realized that I never wrote my "beginners guide to MVC". So I've decided to do exactly that. Here's my "beginners guide to MVC for the web".

He starts with his first lesson, his most important one really - you don't need "MVC" (the concept, not the pattern...he notes them differently). He then gets into what the MVC pattern actually is and describes each piece and how they fit together. Following that, he talks about "MVC" as a concept and how it's different from MVC, the design pattern (hint: the pattern describes one implementation of the MVC ideals). He talks about the role of state in the MVC structure and how the implementation of the MVC idea is slightly different in the various "MVC frameworks" out there.

There is a very useful lesson that MVC brings: Separation Of Concerns. Meaning that you should separate different responsibilities into different sections of your application. Separation of Concerns is a necessary step in dealing with Abstraction. Instead of latching on to MVC, latch on to abstraction. Latch on to separation of concerns. Latch on to architecture. There are far better ways to architect and abstract user interaction for server-based applications than MVC.
tagged: beginner guide mvc modelviewcontroller designpattern concept solid abstraction

Link: http://blog.ircmaxell.com/2014/11/a-beginners-guide-to-mvc-for-web.html

Mathias Verraes:
Resolving Feature Envy in the Domain
Aug 12, 2014 @ 11:55:24

Mathias Verraes has a new post today about something he calls "feature envy" in the domain, related to this code smell (based on a definition from Martin Fowler).

Benjamin Eberlei did a really nice job of explaining refactoring the Feature Envy code smell on his blog. I wrote a comment because I felt the example could be taken one step further. You should read the original post. Below are Benjamin’s code examples (for reference), followed by a repost of my comment.

The "smell" is defined as "a method that seems more interested in a class other than the one it's in". Mathias includes the code examples from the other post showing a datetime calculation and how it could be abstracted out to another class and method. He talks about the migration and how it relates to the "Whole Value" pattern and integrating some of the logic into a factory, generating a "reporting period" instance. He finishes the post with a brief look at an application of domain-driven design concepts to the problem, suggesting that the reporting be even more abstracted from the datetime data and using the "reporting period" object instead.

tagged: feature envy whole value designpattern class object abstraction domaindriven

Link: http://verraes.net/2014/08/resolving-feature-envy-in-the-domain/

Mathias Verraes:
When to Use Static Methods
Jun 16, 2014 @ 10:20:52

Mathias Verraes has followed up his previous post about named constructors in PHP with a bit more clarification about when to use static methods (as he did in his "multiple constructor" examples previously).

Some of the reactions to my last blog post on Named Constructors in PHP, originate from the notion that static methods are inherently bad and should never be used. This is rather overgeneralized. Static methods are nothing more than namespaced global functions. Namespacing, I think we can all agree on, is great. As for global functions: We use those all the time. The native functions in PHP form our basic building blocks.

He talks about the main problem with their use, the shared global state, and compares it to a more stateful service. His solution is to either move to a normal object state (that allows for internal tracking) or think more about abstractions and how they relate.

tagged: static methods opinion object stateless abstraction

Link: http://verraes.net/2014/06/when-to-use-static-methods-in-php/

Anthony Ferrara:
Beyond Design Patterns
Sep 19, 2013 @ 10:43:11

Anthony Ferrara has written up a new post that looks beyond design patterns. He suggests that more emphasis should be put on learning proper methods for abstraction and communication between objects and structures.

Many people teach design patterns as a fundamental step to Object Oriented Programming. They are so universally seen as important that almost every single conference that I have been to has had at least one talk about them. They are quite often used as interview questions to test a candidate's OOP knowledge. However, just like inheritance, they are not needed for OOP. And just like inheritance, they are a distraction rather than a foundation. Instead of focusing on patterns, I suggest focusing on learning about abstraction and communication.

He briefly covers the three types of patterns most people are introduced to - creational, structural and behavioral - and his suggestions of other patterns that answer more of the "what the problem is" question:

  • Shim patterns (Flyweight, Iterator, etc)
  • Compositional patterns (Adapter, Builder, Facade, etc)
  • Decompositional patterns (Bridge, Command, Mediator, etc)

He spends some time later in the post looking a bit more closely at four specific patterns, Adapter, Bridge, Facade and Proxy. He points out that they (essentially) do the same kind of thing and boils it down to a more refined set of implementation patterns and the problems they help solve.

tagged: designpattern communication abstraction implementation problem

Link: http://blog.ircmaxell.com/2013/09/beyond-design-patterns.html