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

How to Validate Data
Nov 10, 2015 @ 10:18:52

In this post to thePHP.cc site Sebastian Bergmann looks at validation data, both in the sense of user input and the contents of objects you're application is currently working with.

Validating data seems to be one of the most important tasks of an application. After all, you cannot trust data from external sources. So let us have a look at how to efficiently implement data validation.

He gives an example of a user profile with requirements on the data it should contain. He focuses on the email address property as it's one of the easier options to validate (or is it). He walks through the usual progression from controller injection to setter injection of the value but wonders when the validation should happen to keep the Profile object from becoming invalid. He points out that simply having a validate method perform the checks isn't enough as it may not always be called correctly, leading to potentially invalid objects. Instead he recommends an alternative - using a validator object/tool in the setters of your object instance as the values are set. This prevents the object from getting into an unknown state and provides immediate feedback to the developer when something's wrong.

tagged: data validation object recommendation setter business rules

Link: https://thephp.cc/news/2015/11/how-to-validate-data

Full Stack Radio:
28: Jeffrey Way and Dave Marshall - "Don't mock what you don't own"
Oct 29, 2015 @ 09:32:52

The Full Stack Radio podcast, hosted by Adam Wathan, has posted their latest episode featuring guests Dave Marshall and Jeffrey Way. In this latest show they suggest you "don't mock what you don't own".

n this episode, Adam talks to recurring guests Jeffrey Way and Dave Marshall about "don't mock what you don't own". They talk about how to design code that needs to work with external services, how you should test that code, and the pitfalls you run into when you use mocks incorrectly in your test suite.

Topics mentioned include this paper suggesting you mock roles not objects and an opinion piece on why integration tests are a scam. You can listen to this latest episode either through the in-page audio player or by downloading the mp3. If you enjoy the show, be sure to subscribe to their feed and follow them on Twitter for information about when the latest shows are released.

tagged: fullstackradio podcast jeffreyway davemarshall mock object testing

Link: http://www.fullstackradio.com/28

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/

Lorna Mitchell:
PHP: Calling Methods on Non-Objects
Oct 19, 2015 @ 10:53:57

In a quick post to her site Lorna Mitchell describes a small difference in error messaging that's changed between PHP versions when trying to call methods on non-objects between versions 5.5, 5.6 and the upcoming PHP 7.

PHP has subtly changed the wording of this error between various versions of the language, which can trip up your log aggregators when you upgrade so I thought I'd give a quick rundown of the changes around the "call to member function on non-object" error in PHP, up to and including PHP 7 which has an entirely new error handling approach.

She includes examples of the error messages for PHP 5.5 and 5.6, differing only in how they report back the type of the variable the method was called on (one gets more specific). In PHP 7, however, the message is different because of the major overhaul that error handling has gotten. The new Error inheritance model still has it throw a fatal but it also notes it's an uncaught error which can be caught with the same try/catch as any other exception.

tagged: object error message version php5 php7 example output uncaught

Link: http://www.lornajane.net/posts/2015/php-calling-methods-on-non-objects

Bernhard Schussek:
Value Objects in Symfony Forms
Sep 10, 2015 @ 11:35:20

Bernhard Schussek has posted a tutorial on his Webmozart.io site talking about the use of value objects in Symfony forms. By nature value objects don't allow the use of "setters" to assign/change values but he shows how to use a custom data mapper to work around the problem.

Many times, Symfony developers wonder how to make a form work with value objects. For example, think of a Money object with two fields $amount and $currency. [...] Can you write a form type for this class without adding the methods setAmount() and setCurrency()? In this post, I will show you how.

He starts with a bit of an overview on what value objects are and how the concept of immutability comes into play. He shows examples of potential issues if setters are allowed to change data and what should be done when a value change is actually needed. He then gets into the heart of the matter, integrating the forms handling with simple value objects. He goes through building a simple form and the use of the empty_data option to create a new value object with the form values. This works fine but breaks down if you need to update an object. Instead he creates a custom data mapper that sets up two methods, mapDataToForms and mapFormsToData, that allow for both interactions to work correctly.

tagged: value object symfony form tutorial custom data mapper emptydata

Link: https://webmozart.io/blog/2015/09/09/value-objects-in-symfony-forms/

Joe Fallon:
Immutable Objects in PHP
Aug 27, 2015 @ 11:53:36

Joe Fallon has a post to his site talking about immutable objects in PHP, objects that once the property values are set they cannot change.

When I first learned to program, I made many objects that were mutable. I made lots of getters and lots of setters. I could create objects using a constructor and mutate and morph the heck out of that object in all kinds of ways. Unfortunately, this led to many problems. My code was harder to test, it was harder to reason about, and my classes became chock full of checks to ensure that it was in a consistent state anytime anything changed.

[...] Now, I favor creating immutable objects. The folks over in the functional camp are super excited about this concept. However, it’s been around for quite a while and it has so many benefits.

He talks about how immutable objects make it easier to not only test code but also allow for more rational reasoning about their contents. He points out that they also make it easier to understand the state of an application should an exception arise. He then gets into some examples of immutable objects, creating an ImmutableClass and a ImmutableClassBuilder to help create instances based on values provided.

tagged: immutable object introduction class builder example benefits

Link: http://blog.joefallon.net/2015/08/immutable-objects-in-php/

Ahmad Hajjar:
Mocking Objects for Unit Testing in PHP Using Go! AOP
Aug 18, 2015 @ 11:55:01

In an interesting post to his blog Ahmad Hajjar shows you how to use to Go! PHP AOP framework to help mock objects in your unit tests. The Go! AOP framework provides some of the base functionality for using aspect-oriented programming techniques in your code.

These have been always very important questions in software development industry; what should I test in unit testing? And how can I make tests as small as possible, and how to avoid testing already tested code? or 3rd party libraries? [...] In principle, unit test must fail for one and ONLY ONE reason, this makes sense actually, as it complies with the S in the SOLID object-oriented design principles. [...] We can use mocks in the problem listed above, to make the unit test, real unit test, that is testing only the things that needs to be tested. [...] However, what we are going to do today is something different. OK! Why should we re-invent the wheel? the answer is : because it is simpler wheel ! also it is a wheel that uses different technology which is AOP.

He uses a simple Laravel application and the Go! framework for his testing examples. He uses the AOP functionality from Go! as the mock handling instead of something like PHPUnit's own mocking or Mockery. He shows how to configure the AOP functionality first, then creates a basic aspect class with a few interceptors for method calls. He creates an AopMocker class that adds the class requested to the mock configuration. Finally he improves the initial unit test example using these tools, building mocks for User and Post classes and making the same assertion.

tagged: unittest mock object aop aspectoriented programming goaop framework

Link: https://ashajjar85.wordpress.com/2015/08/16/mocking-objects-for-unit-testing-in-php-using-go-aop/

PHP Object-Oriented Programming Beginner's Guide
Aug 12, 2015 @ 09:45:14

For those working to move from procedural PHP into a more object-oriented world but may be having some trouble with the transition, the Star Tutorial site has a great beginner OOP in PHP guide you should check out.

They cover all of the basics you'll need to get started with objects in PHP including:

  • classes versus objects
  • visibility
  • inheritance
  • polymorphism
  • interfaces versus abstract classes

Each section is a quick definition and a bit of code to help illustrate the point. This isn't going to be a hand-holding kind of tutorial showing you each step to making an OOP application. Instead, it provides quick, high level summaries of the main OOP concepts to get you on the right road.

tagged: oop object beginner concepts guide tutorial section concepts

Link: http://www.startutorial.com/homes/oo_beginner

Freek Lijten:
Value objects
Jul 16, 2015 @ 10:17:14

Freek Lijten has written up a post looking at value objects, how he feels they're not used enough in modern development and a few practical applications of them in action.

I would like to talk about value objects for a bit. Value objects are very underused, very powerful and general good stuff. They might not change your world but they will change, very subtle, a lot of the code you write. I hope to give the shortest possible introduction to the concept and follow up with a couple of example that make me like value objects so much.

He briefly introduces some of the basics of value objects including one of the main points: their immutability. He gives an example of working with a "10 Euro" object, pointing out that once an operation is performed using it, it becomes a different object not just one with a value changed. He also illustrates with an email address example pointing out that email addresses themselves (not the relation to the user) almost never change. He ends the post with another interesting value object scenario using IDs and making them type hint-able.

tagged: value object

Link: http://www.freeklijten.nl/home/2015/07/16/Value-objects

Julien Pauli:
PHP closures
Jul 10, 2015 @ 10:54:29

Julien Pauli has posted a look at PHP's closures and how they're actually handled internal to the language.

Back in 2009, when PHP 5.3 got released, a new feature (among many others) were introduced : anonymous functions (also called lambdas or closures). The feature was very expected, as closures have proved their utility through several other languages, particularly javascript that web developers master. [...] Let's see together how Closures have been added to PHP, as usual by turning to the truth : the PHP source code.

He starts at the beginning (a good place to start) and talks about the work that needed to be done on the internals before closures could even be introduced. He walks through the changes made to object handling to make them "callable" and the addition of the "zend_closure" object type. He then gets to the part where "the magic happens" and shows how the userland closure is translated and executed. He ends the post with a look at two other topics: scoping with "$this" and the special handling that was needed for reflection and direct calls to "__invoke".

tagged: closure language functionality object callable scope reflection invoke

Link: http://jpauli.github.io/2015/07/08/php-closures.html