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

QaFoo Blog:
Outside-In Testing and the Adapter and Facade Patterns
Jul 05, 2016 @ 10:47:03

The QaFoo blog has a post today about outside-in testing, two design patterns - Adapter and Facade - and how they relate.

As part of our workshops on Test-Driven Development we explain to our customers how testing from the outside-in can help find the right test-mix.

The technique puts a focus on test-driven-development, but instead of the traditional approach starts at the acceptance test level. The first test for a feature is an acceptance test and only then the feature is implemented from the outside classes first. [...] Outside-In testing leads to interfaces that are written from what is useful for the client object using them, in contrast to objects that are composed of collaborators that already exist. Because at some point we have to interact with objects that exist already, we will need three techniques to link those newly created interfaces/roles to existing code in our project

These three techniques are:

  • using the adapter pattern to interface with third party code
  • the facade pattern to "layer" your own code
  • continuous refactoring of interfaces/implementations

In this post they focus mostly on the adapter pattern. They show how to use it in interfacing with remote systems in a Symfony application (for example) based on a remote XML file. They also include the test to verify it's functioning correctly and the PHP code to make the mocks and interfaces you'll need for the test.

tagged: outsidein testing adapter facade designpattern refactor interface

Link: https://qafoo.com/blog/087_outside_in_testing_adapter_pattern.html

SitePoint PHP Blog:
Disco with Design Patterns: A Fresh Look at Dependency Injection
Jul 01, 2016 @ 11:26:44

On the SitePoint PHP blog there's a tutorial posted giving you a "fresh look at dependency injection" using the Disco library from bitExpert.

Dependency Injection is all about code reusability. It’s a design pattern aiming to make high-level code reusable, by separating the object creation / configuration from usage.

[...] Our very own Alejandro Gervasio has explained the DI concept fantastically, and Fabien Potencier also covered it in a series. There’s one drawback to this pattern, though: when the number of dependencies grows, many objects need to be created/configured before being passed into the dependent objects. [...] In this article, we’ll demonstrate the concept [of a dependency injection container] further with a newcomer in this field: Disco.

He starts with the installation of the library via Composer and starting up the built-in PHP web server for testing. With that up and running he shows you how to create an instance of the container and set up a sample service with the configuration in the docblock comments. The tutorial then talks about the service scopes, container parameters and shows it in action to create a simple controller handling frontend. There's a bit more about configuration, the container builder functionality and the creation of a response listener when routes are requested.

tagged: tutorial disco designpattern dependency injection di library

Link: https://www.sitepoint.com/disco-with-frameworks-and-design-patterns-a-fresh-look-at-dependency-injection/

Marko Pavlovic:
Restful Commander
Mar 23, 2016 @ 11:55:10

In this post to his site Marko Pavlovic talks about REST APIs, some of the non-CRUD (create, read, update, delete) operations that need to be performed and how the Command design pattern can help.

We’ve all been here: the data model has been designed, and we have the entities and relationships implemented. It is finally time to code up the business logic and we are faced with solving these problems: The actions we want to implement on a particular model are not part of the good old CRUD (Create, Read, Update, Delete) operations, and we need to make a lot of non-standard controller actions, and routes. [Also] the actions we want to implement do not belong to a any model, and we have to create a new controller just for the "API".

He gives a more concrete example to illustrate the problem using "sites", "visits" and a desire to add analytics functionality using each's data. He points out two common actions taken when something like this comes up: either new methods on the pre-existing controllers or possibly making a new controller to handle it. Instead he suggests using the Command pattern to handle requests themselves as self-contained items. This gathers all the logic needed in to one place and the Report instance can then be used as-is by the response that needs to render the results.

tagged: rest api command designpattern report site visit

Link: http://markonis.github.io/rest/api/design-patterns/2016/02/23/restful-commander.html

The Repository Pattern in Laravel 5
Mar 15, 2016 @ 12:50:05

The TutsPlus.com site has posted a tutorial covering the use of the repository design pattern in Laravel, a popular PHP framework. While the article does introduce some of the basics of the design pattern, a bit more research may be in order if you're not familiar with its base concepts.

The repository pattern was introduced for the first time by Eric Evans in his Domain-Driven Design book. The repository is, in fact, the entry point for the application to access the domain layer.

To put it simply, the repository allows all your code to use objects without having to know how the objects are persisted. The repository contains all the knowledge of persistence, including mapping from tables to objects. This provides a more object-oriented view of the persistence layer and makes the mapping code more encapsulated.

In this article they replace the default storage/persistence method for database records away from the default Eloquent over to Doctrine, a widely used ORM tool. The start with a brief comparison between Eloquent and Doctrine before starting on on a simple "blog" application. They connect Doctrine to Laravel via an "entity manager" and make a basic Doctrine-based model for the Posts and a matching repository/controller implementation. All the code you'll need to implement it is included along with a simple view to take in the post content and display errors if there were any on the save.

tagged: repository designpattern laravel tutorial doctrine eloquent blog

Link: http://code.tutsplus.com/tutorials/the-repository-pattern-in-laravel-5--cms-25464

SitePoint PHP Blog:
Command Buses Demystified: A Look at the Tactician Package
Jan 27, 2016 @ 10:47:44

On the SitePoint PHP blog there's a tutorial posted that wants to help demystify the command bus design pattern with the help of the Tactician package, a part of the packages from The PHP League.

Command Buses have been getting a lot of community attention lately. The topic can be quite overwhelming at first when trying to understand all the concepts and terminology, but in essence – what a Command Bus does is actually incredibly simple.

In this article, we’ll take a closer look at variations of the Command Pattern; their components; what a Command Bus is; and an example application using the Tactician package.

The article starts with a look at what the Command Bus design pattern is and where it could be put to use in an application. There's a bit of sample code showing how to implement a basic bus and the commands it would be used to execute. Their example application uses a "deck of cards" set of actions. They show how to use the Tactician library to build and execute three related commands: CreateDeck, ShuffleDeck and DrawCard. They show you how to build out the pieces you'll need - the extractor, locator and middleware - and join them all together to execute the commands.

tagged: tutorial tactician package commandbus designpattern introduction

Link: http://www.sitepoint.com/command-buses-demystified-a-look-at-the-tactician-package/

Paul Jones:
Atlas: a persistence-model data mapper
Dec 30, 2015 @ 09:48:50

Paul Jones has a new post to his site about a library he's worked up to provide "persistence-model data mapper" functionality for you to use in your PHP applications in accessing your database.

Atlas is a data mapper implementation for your persistence model (not your domain model).

As such, Atlas uses the term "record" to indicate that its objects are not domain entities. Note that an Atlas record is a passive record, not an active record; it is disconnected from the database. Use Atlas records indirectly to populate your domain entities, or directly for simple data source interactions.

The library is mostly an experiment on his part to create a tool that allows switching from the Active Record pattern to Data Mapper pattern for accessing your database without much hassle. The README on the library shows some of the basic usage of the tool, including the usual CRUD (create, read, write, execute) functionality.

tagged: atlas persistence model datamapper activerecord designpattern database library

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

SitePoint PHP Blog:
Modeling an Aggregate with Eloquent
Nov 30, 2015 @ 11:49:19

The SitePoint PHP blog has a tutorial posted from Andrew Cairns showing you how to model an aggregate with Eloquent, the database access layer from the Laravel framework. The "aggregate" here is an implementation of the Aggregate design pattern, a system of smaller opbjects operating as a whole.

The Aggregate pattern is an important part of Domain Driven Design. It prevents inconsistencies and is responsible for enforcing business rules within a collection of objects. For these reasons alone, it is clear to see why it is a key component of a domain model.

[...] Mixing persistence concerns into a Domain Model can become complex and lead to a lot of bad decisions. This does not mean that it is impossible to create an Active Record Domain Model. In this article, we will work through an example of building an Aggregate which also extends Eloquent: a popular Active Record ORM.

They start with a brief summary of what the Aggregate design pattern, how its objects work together and the point of a "root" object. They help illustrate how it would in a more real-world situation with a simple blog system, starting with a simple Post object minus the Eloquent integration. From there they bring in Eloquent, showing how to extend it with the class and what features it introduces. Most of the changes they make then revolve around a "lock" on the post and where value objects and the invariant rule comes in to play.

tagged: aggregate eloquent designpattern domaindrivendesign tutorial

Link: http://www.sitepoint.com/modeling-aggregate-eloquent/

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/