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

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/

Laravel News:
Learn to use Model Factories in Laravel 5.1
Oct 08, 2015 @ 10:46:21

On the Laravel News site there's a tutorial helping you learn to use Model factories in your Laravel 5.1+ application. These factories make it easy to create instances of "fake" models that can be interacted with as if they were the real thing.

These have several use cases with the two biggest being–testing and database seeding. Let’s take a deeper look at this feature by building out the beginning of a little fictional app.

They provide a situation where these factories can solve a potential problem: making an application easier to test because of the (potentially) high volume of customers. He walks you through the creation of a new application and building out the models and matching migrations. Next up is the generation of the database seed values and, finally, the creation of the fake models and the code needed to connect it all together. The post ends with a look at using these factories to generate models in tests, creating them with simple data and some of the other features they offer.

tagged: model factory laravel fake tutorial testing introduction

Link: https://laravel-news.com/2015/10/learn-to-use-model-factories-in-laravel-5-1/

Rob Allen:
Custom OAuth2 authentication in Apiiglity
Jul 21, 2015 @ 09:05:49

In an article posted to his site Rob Allen shows you how to hook in the OAuth2 authentication for an Apigility-based application with a pre-existing database table structure that may not match the defaults Apigility is looking for.

I have a client that's writing an Apigility API that needs to talk to a database that's already in place. This also includes the users table that is to be used with Apigility's OAuth2 authentication. Getting Apigility's OAuth2 integration to talk to a specific table name is quite easy. [...] However, if you want to use different column names, that's a bit trickier as they are hardcoded in the OAuth2StoragePdo class. To get Apigility's OAuth2 components to look at the correct columns, you create your own OAuth2 Adapter. I chose to extend ZFOAuth2AdapterPdoAdapter which extends OAuth2StoragePdo and go from there.

He includes the code for this extension of the PdoAdapter (a "OAuth2Adapter" class) in the post showing the definitions of the get user, set user and check password methods the OAuth2 flow needs to match users to OAuth sessions. He also includes the code for the "OAuth2AdapterFactory" class that's used to pull the custom PDO adapter class into Apigility and, along with some configuration changes, make it available for use. Then it's just a simple matter of changing the authentication type in the Apigility UI.

tagged: apigility oauth2 authentication custom factory pdo adapter oauth tutorial

Link: http://akrabat.com/custom-oauth2-authentication-in-apiiglity/

Paul Jones:
A Factory Should Create, Not Retain
Jul 08, 2015 @ 08:45:31

Paul Jones has posted his thoughts about factory behavior in PHP applications (well, really any kind of application as it's a pan-language concept). He suggests that factories should only create the objects requested and not persist them.

In a recent Reddit conversation, some of us went off on a tangent about factories. I maintained then, and do now, that a “factory” always-and-only returns a new instance. If you have a “factory” that returns anything other than a new instance, it’s not a factory alone. In the case of factory methods, it is a factory + accessor; in the case of factory objects, it is a factory + registry. A “factory” (whether a factory method or factory object) is one way to separate object creation from object use.

He gives an example of a case where an object needs to be created for a "doSomething" method. His first example shows the creation of the "Item" inline, mixing the creation and use of the object into the same place. He replaces this with a "factory" class/method that only returns the new "Item" requested. He points out that a factory method that retains the object (like as a class property) has the same problem as the first example - retention. Instead he suggests an intermediate "collaborator" that splits out the creation and retention once again.

tagged: factory retain create object method collaborator example

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

Stephan Hochdörfer:
Simple Logging Facade for PSR-3 loggers
Jun 17, 2015 @ 09:56:45

In his latest post Stephan Hochdörfer shares a library he's created to hopefully make it easier for developers to integrate PSR-3 compatible logging libraries into their code, a "logging facade" based on an idea from the Java world.

Lately I have seen more and more libraries picking up PSR-3 when it comes to logging. What a lot of libaries do wrong is that they depend on a concrete implementation of PSR-3, e.g. Mongolog instead of relying on the PSR-3 interface. From what I have seen this is because loggers get instantiated directly within the class. This is not a bad thing but it couples your code to a concrete implementation of PSR-3 which in turn means that there`s no interoperability.

The Java community solved the problem by creating a Simple Logging Facade library (SLF4) which I "ported" to PHP last week.

The library makes provides a simple static interface to setting the PSR-3 logger of your choice and fetching it from anywhere in your application. He includes an example of what the code would look like for a basic Monolog instance. He ends the post talking about this method for getting/setting the logger instance and how it compares to using other options like a dependency injection container or even just a manual call to a setter.

tagged: logger facade factory psr3 monolog example library

Link: https://blog.bitexpert.de/blog/simple-logging-facade-for-psr-3-loggers/

Marc Morera:
Defeating Expression Language
May 18, 2015 @ 08:38:27

Marc Morera has a new post to his site wanting to help you defeat Symfony's expression language and perform the same functionality, just more on the code side (another option).

How beautiful Expression Language definitions are, right? I mean, inserting that complex expressions in a Dependency Injection configuration file is so nice and fast if you need to inject the result of a method in a service (one of the multiple examples we can see). [...] This is not a bad idea, really, but because we are engineers and we should have as much information as possible in order to be able to choose between the best option, always, I will show you another way of defining this piece of code.

He shows how to write some code using the Factory design pattern structure to reproduce a bit more complex piece of expression language. He shows the setup of the services.yml file to define the "managers" and classes/services to be injected. He also notes that this removes the need for the "symfony/expression-language" dependency and makes things more portable in the future.

tagged: expression language symfony alternative factory dependencyinjection services configuration

Link: http://mmoreram.com/blog/2015/05/18/defeating-expression-language/

Design Patterns: The Simple Factory Pattern
Jan 27, 2015 @ 11:53:20

NetTuts.com has posted the next part of their series focusing on design patterns (and more specifically implementing them in PHP). In this latest post they look at a simple version of the Factory design pattern.

When you think of a factory, what comes to mind? For me, it's a place where things are created - that is, it's a centralized placed where things are produced. Later, the delivery of said products are done by the factory based on an order. Let's say that you're requesting a car. A factory will create one based on the specifications of the work order and will then deliver it once it's complete. Just as their real world counterparts, a software factory (that is, software that implements the factory design pattern), is an object that is responsible for creating and delivering other objects based on incoming parameters.

They mention the three different versions of the factory pattern but focus in on the simplest one (hence the "simple" in the title). They continue on with the car example, showing how to use a simple factory (a "carFactory") to build an instance of the "Car" class based on different classes of car types. The object is constructed when a "build" method is called with the type.

tagged: designpattern simple factory car type example tutorial introduction

Link: http://code.tutsplus.com/tutorials/design-patterns-the-simple-factory-pattern--cms-22345

Master Zend Framework:
Configuring the ServiceManager with Abstract Factories
Jul 23, 2014 @ 13:41:10

On the Master Zend Framework site today Matthew Setter has a new post covering the configuring of the service manager using abstract factories.

One of the best features about Zend Framework 2 is undoubtedly the ServiceManager; because it makes it almost painless to configure and retrieve services in a consistent and predictable manner, anywhere in your application, at any time. [...] But the catch is, there’s quite a bit to learn if you want to use it properly. As well as that, there’s quite a number of ways to use it.

He walks you through some of the pros and cons of the various ways to work with the ServiceManager and where the factories fit in. He takes a bit of time to introduce the concepts behind abstract factories and how to define them in a Zend Framework v2 application. He finishes out the post with a more practical, working example using the interfaces provided to get a "MyUserTable" service.

tagged: configure servicemanager abstract factory tutorial screencast

Link: http://www.masterzendframework.com/servicemanager/configuring-servicemanager-with-abstract-factories

Exploring PHP Design Patterns
Jun 23, 2014 @ 10:41:50

For those that might be new to development, the concept of "design patterns" could be one you're just approaching. These common practices define some "patterns" of development that have been proven to provide good structure and maintainability to applications...when applied correctly. PHPBuilder.com has an introductory article showing you how to use five of the most common patterns: Factory, Singleton, Observer, Chain of Command and Strategy.

Design patterns provide a generic reusable solution to common problems. A design pattern is not a concrete solution that can be converted in to source code or a machine code rather it is a template which can be used to solve a problem in different situations. Design patterns help in faster development as the templates are proven and from the developer's point, only implementation is required. Design patterns not only make software development faster but also encapsulate big ideas in a simpler way.

For each of the patterns represented a brief description is included and some sample code is given showing it in use. There's not too much depth in this post, so if you're looking for more "meat" on these patterns, I'd suggest checking out some more advanced articles on SitePoint.com.

tagged: introduction designpattern factory singleton observer chainofcommand strategy

Link: http://www.phpbuilder.com/articles/application-architecture/design/exploring-php-design-patterns.html

Mathias Verraes:
Named Constructors in PHP
Jun 13, 2014 @ 09:42:15

Mathias Verras has a new post to his site about an idea he calls "named constructors". This method uses static factory methods to simulate the idea of a constructor and initialize the object.

PHP allows only a single constructor per class. That’s rather annoying. We’ll probably never have proper constructor overloading in PHP, but we can at least enjoy some of the benefits. Let’s take a simple Time value object. Which is the best way of instantiating it? The only correct answer is “it depends”.

His example shows the typical constructor creation with variable arguments, but points out that this can get messy quickly. His other method, the factory methods as "constructors", can make for a cleaner interface and makes the class more flexible. They make the object able to be initialized with different types of values and even satisfies the Single Responsibility Principle. He goes through a few examples using his "Time" class, showing how different "constructor" methods can be used to handle inputs ranging from a normal hour/minute format out to a "from minutes since midnight" value.

tagged: named constructor factory method static tutorial time

Link: http://verraes.net/2014/06/named-constructors-in-php/