Looking for more information on how to do PHP the right way? Check out PHP: 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

PHP Roundtable:
033: Design Patternmania
Oct 27, 2015 @ 09:39:26

The PHP Roundtable podcast has posted their latest episode today, Episode #33 - Design Patternmania. This episode features guests Adam Wathan, Anthony Ferrara and Ross Tuck discussing design patterns with host Sammy Kaye Powers.

With a new design pattern coming out every week it can be easy to get caught up in all the hype. If you frequently try to implement the latest-and-greatest design pattern and feel constantly paralyzed by the thought, "I know I'm doing this wrong," this episode is for you.

We discuss how "not seeing the forest for the trees" might be a good thing as we try to narrow our focus in order to write better code without thinking of patterns first.

You can catch this latest episode either through the in-page video player or directly on YouTube. If you enjoy the show, be sure to subscribe to their feed and follow them on Twitter to get information about the latest shows as they're released (and when future live recordings are happening).

tagged: phproundtable podcast video designpattern adamwathan anthonyferrara rosstuck

Link: https://www.phproundtable.com/episode/keeping-code-simple-in-a-design-pattern-world

SitePoint PHP Blog:
Flyweight Design Pattern and Immutability: A Perfect Match
Oct 22, 2015 @ 11:56:32

The SitePoint PHP blog has a tutorial they've posted (from author Andrew Carter) looking at the Flyweight design pattern and immutability, how they're a "perfect match". The flyweight pattern makes it possible to reuse objects after they've been created with one requirement: they must be immutable.

The fundamental principle behind the flyweight pattern is that memory can be saved by remembering objects after they have been created. Then, if the same objects need to be used again, resources do not have to be wasted recreating them. [...] You can think of the flyweight pattern as a modification to a conventional object factory.

One important feature of flyweight objects is that they are immutable. This means that they cannot be changed once they have been constructed. This is because our factory can only guarantee that it has remembered the correct object if it can also guarantee that the object it originally created has not been modified.

The post includes code examples of how to implement the pattern with a simple File object that fetches data from a file when created. He then creates the factory class, with a getFile method that takes in the path and creates the immutable File object from it. It's then stored in an internal array for potential reuse later. He also talks about how the pattern could be useful for handling enumeration objects and how you can use it to build out "type" objects.

tagged: flyweight designpattern immutable object factory tutorial type enumeration

Link: http://www.sitepoint.com/flyweight-design-pattern-immutability-perfect-match/

Paul Jones:
Service Classes, Payloads, and Responders
Aug 12, 2015 @ 10:52:27

Paul Jones has written up a post talking about service classes, payloads and responders and how they can help pull logic out of controllers and into more reusable chunks. It's inspired by comments and methods mentioned in another earlier post from Revath Kumar.

Revath Kumar has a good blog post up about extracting domain logic from controllers and putting that logic in a service class. After reading it, I commented that with a little extra work, it would be easy to modify the example to something closer to the Action-Domain-Responder pattern. In doing so, we would get a better separation of concerns (especially in presentation).

Paul applies some of the concepts that Revath outlined to the ADR pattern, suggesting that service classes should always return Payloads and the reduction of functionality in the controller overall. He includes an example of what the resulting code would look like, following along with the "orders" scenario outlined in Revath's post.

tagged: service class payload responder adr action domain responder designpattern

Link: http://paul-m-jones.com/archives/6172

SitePoint PHP Blog:
Introduction to Chain of Responsibility
Jun 24, 2015 @ 10:26:17

The SitePoint PHP blog has a recent post where they dig into the details of the Chain of Responsibility design pattern, a commonly used structure that makes for easier workflow handling and encapsulation.

The Chain of Responsibility is a behavioral design pattern that processes a request through a series of processor (handlers/receivers) objects. The request is sent from one handler object to another and processed by one (pure implementation) or all of the handlers. All the handlers are part of the chain.

They get into the detail of the parts of the pattern first: the abstract handler that defines the structure and a set of concrete handler classes based on this structure. He also mentions a few other object types that could be involved including a Client, Request and Response objects. He includes an example of the base abstract handler class with "setSuccessor" and "handler" methods to provide the "chain" from one handler to another. He creates a more advanced version of the handler that does some additional checking on the handler results to see if it needs to continue. Finally, he gets down to the Client class that handles the ordering of the chain before processing. He also shows how a service container (dependency injection) could be integrated to manage creating object instances.

tagged: chainofresponsibility designpattern tutorial order workflow

Link: http://www.sitepoint.com/introduction-to-chain-of-responsibility/

Ed Zynda:
Aspect Oriented PHP And The Interceptor Pattern
Jun 12, 2015 @ 09:51:23

Ed Zynda has a recent post to his site looking at the use of the Interceptor design pattern with the aspect oriented methodology in PHP. He doesn't get into the basic concepts of AOP, so you might want to find out a bit more in other places. It's not a necessity, though, as his code examples are easy enough to follow along.

There are many ways to modify the behavior of existing code with actually changing the core logic. Some patterns you might be familiar with are the decorator pattern or the observer pattern. Both allow you to take another object and modify the behavior by wrapping your modifications around the original code. One pattern you might not be familiar with though, is the interceptor pattern.

He first helps you install the AOP-PHP extension to provide some of the necessary PHP functions. From there he talks about using some of the functions that intercept function calls and perform an action. He shows examples of it using:

  • aop_add_before
  • aop_add_after
  • aop_add_around

He also shows how to modify arguments during execution and changing return variables when the execution of the function is completed.

tagged: aspectoriented programming aop designpattern interceptor

Link: http://www.edzynda.com/aspect-oriented-php-and-the-interceptor-pattern/

Marc Aube:
Design Pattern: Specification
May 25, 2015 @ 12:19:47

Marc Aube has a new post to his site that introduces you to the specification design pattern, a technique that's useful for ensuing the current state of an object is valid.

The specification pattern is a software design pattern used to codify business rules that state something about an object. These simple predicates determine if an object's state satisfies a certain business criteria. They can then be combined to form composite specifications using logical operators. Use a specification to encapsulate a business rule which does not belong inside entities or value objects, but is applied to them.

He suggests a few things the pattern could be useful for like validating the current state or define how an object should be created. He gives a few more "real world" examples and then gets into the code to create a custom specification. In his "CustomerIsPremium" spec he defines a single method on an interface to determine if the Customer given is correct. He then creates a class instance and encapsulates the logic inside its "isSatisfiedBy" method. He also includes a bit more complex example, showing how to create a composite specification for handling grouping like "and", "or" and "not" assertions. Finally he looks at how to build specifications that can be passed in and used as selection criteria. He does point out that this can leak database handling into the specification layer, however, and should really be avoided without a inversion of control method in place.

tagged: specification designpattern pattern example composite select validate

Link: http://marcaube.ca/2015/05/specifications/

I feel like events are an anti-pattern
May 06, 2015 @ 10:55:00

On the /r/php subreddit frm Reddit.com, phpdevster proposes an interesting opinion - that an event system, set up with a listener and defined events, has become more of an anti-pattern in its most common implementation.

If events are only meant to be additional functionality that ALWAYS ALWAY ALWAYS should happen after a primary action is taken, how often is code really that absolute? Why are events not implemented in more flexible ways by frameworks? - that is implementing some inversion of control which would allow callers to determine which listeners would be relevant to the given context.

He illustrates his point with an example user registration system that fires a "user-was-registered" event that, in turn, fires off a series of events via a listener. He points out a pretty large flaw, though. While the functionality involved in the event is decoupled (the event itself), the behaviors defined by that event are not. Comments on the post offer some different options and solutions to the same problem including:

  • Further decoupling of the eventing process
  • Using objects with settable properties rather than just event name strings
  • The idea of using an "event store" to handle decoupling rather than more immediate code-based solutions

Have some thoughts of your own on events and decoupling? Go over and share them too.

tagged: event antipattern designpattern reddit opinion comments

Link: http://www.reddit.com/r/PHP/comments/34zp6j/i_feel_like_events_are_an_antipattern/

David Lundgren:
When does Dependency Injection become an anti-pattern?
Apr 23, 2015 @ 12:11:53

In a new post to his site David Lundgren wonders when dependency injection becomes an anti-pattern when used in PHP applications. The idea of dependency injection is to provide objects with instances of other objects representing things they'll need to get the job done (goes along with separation of concerns). Unfortunately, if used incorrectly, DICs - dependency injection containers - can become less useful and more of a hinderance than a positive part of the application.

During my tenure as a seasoned, and tenderized, PHP developer I have used many design patterns: adapters, factories, data mappers, facades, etc. The most recent one that I have been working with is Dependency Injection. Inversion of Control is not a new idea, at least not in the programming world, but in the PHP world it seems to have taken us by storm in recent years. Every framework will often have a Dependency Injector built in, or offer it as a component for use. It is the hip thing to do in PHP, but I believe we need to take a step back and evaluate it for what we are really trying to achieve. That is reducing the tight coupling that our objects may have. I view it as removing the new-able’s from our objects code, and handing the object creation over to something else to deal with.

He talks about how dependency injection containers and service locators relate to each other. He also suggests that, at the heart of every dependency injection container, there's a service locator. He gives an example of a project where a large number of dependencies are being injected and how, despite the assumption of flexibility, his dependencies don't change that often, making the DIC and its functionality a bit less important.

tagged: dependencyinjection dic servicelocator antipattern designpattern opinion

Link: http://davidscode.com/blog/2015/04/17/when-does-dependency-injection-become-an-anti-pattern/

Design Patterns: The Singleton Pattern
Apr 14, 2015 @ 12:31:44

On the NetTuts.com site today they've posted another in their series introducing the various design patterns that have been established in software development. In this new post they talk about the Singleton pattern (or "anti-pattern" as it's sometimes called).

In this article you are going to learn how to implement the Singleton design pattern, and why and when to use this pattern in your application. As the name "Singleton" suggests, this method allows us to create one and only one object of a class.

They start with a basic definition of the pattern that, at its heart, is about reusing one and only one instance of an object. To help make it more concrete, they include an example that's refactored to use the Singleton pattern: creating and reusing single instances of database connections (PDO). The article also talks a bit about the idea of the Singleton being an anti-pattern and how it can make things like unit testing difficult.

tagged: designpattern tutorial series singleton introduction

Link: http://code.tutsplus.com/tutorials/design-patterns-the-singleton-pattern--cms-23073