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

Tomas Votruba:
How to Get PHP 7.4 Typed Properties to Your Code in Few Seconds
Nov 19, 2018 @ 15:56:22

Tomas Votruba has a new post to his site showing you how you can get typed properties in your code "in a few seconds", a feature coming in the next major version of the language, PHP 7.4.

PHP 5.6 and 7.0 is going to be dangerous since 2019, PHP 7.1 is new baseline and PHP 7.3 is just about to be released in the end of 2018.

Is this the best time to upgrade your code to PHP 7.4?

He starts off by talking about the use of the @var annotation (DocBlock format) and how, while they can be informative, do nothing functionally speaking. He shows how to shift this over to a typed property, forcing the value to be an integer. He also covers current use of "best practices" when it comes to typing properties and how to think about future compatibility. He ends the post with the command you'd need to use - making use of the rector reformatter - to shift all of those @var annotations over to actual typed properties.

tagged: typed property php74 tutorial reformat var docblock comment

Link: https://www.tomasvotruba.cz/blog/2018/11/15/how-to-get-php-74-typed-properties-to-your-code-in-few-seconds/

Exakat Blog:
5 usages of static keyword in PHP
Jun 20, 2018 @ 15:28:21

On the Exakat blog there's a new post sharing five uses of the "static" keyword in PHP applications. This includes the less common static closures and static class names.

Static is a PHP keyword with many usages. It is almost universally used, though there are many variations of it. Let’s review all the five of them :
  • static method
  • static property
  • static closure
  • static variable
  • static as a classname

The post goes through each of the items in the list giving a brief explanation of how it's used and a code example showing it in action. The post finishes with some tips on evaluating your own code for the use of "static" and tips for each to make your code easier to wrangle and maintain in the future.

tagged: static keyword example tutorial method property closure variable classname

Link: https://www.exakat.io/5-usages-of-static-keyword-in-php/

Freek van Der Herten:
When empty is not empty
May 21, 2018 @ 14:38:08

As PHP developers, dealing with the "helpful" automatic type shifting the language performs can sometimes be challenging. It can lead to some interesting situations like the one Freek van Der Herten has posted about where something that seems "empty" actually isn't.

Recently when I was working on a project I got some strange results when using the empty function. That's really odd [that the result was a string and "empty" when a value was set]. How can a variable hold a string and be empty at the same time?

He includes a few other tests on the same object and firstName property using other "empty" checks with isset and is_null. Those behaved as expected so he started to look more into the class the object is based on. In the class values/properties are returned via magic methods, not direct functions. In the case of empty, this fetching isn't interpreted prior to the check and the result appears "empty". To fix the issue, he recommends implementing an __isset magic method that will then get called to ensure the value is actually set before fetching it.

tagged: language isset empty property tutorial

Link: https://murze.be/when-empty-is-not-empty

Mark Baker:
Discharging Static #2
Apr 05, 2018 @ 15:22:09

Mark Baker continues his series looking at the use of static properties and methods in applications and how to test them. In this second part of the series he focuses more on some of the unintentional side-effects that could happen when you're trying to refactor them out.

In the first article in this series, I wrote about the problems with testing static methods in classes, and showed a few approaches that allow us to write mocks for statics. Testing classes where we have static properties is a lot harder to manage, because any changes made in any test to those properties are global, across the entire test suite, not simply the test that we are running. Static properties are part of the global state, and we can’t simply tearDown() those changes in the way that we do with instances — at least we cannot easily do so if the property has a visibility of private or protected.

He goes through an example of a refactor from a static property (essentially in the global scope) to a private property. He points out the issue of setting a static value in what seem to be separate child classes, the fact that it actually changes the base value, not the individual ones, leading to potentially unintended consequences.

His main recommendation is to avoid the use of static properties all together. Where that's no possible (like in a legacy project) he offers two potential solutions: either replace them with constants if they're never changed or changing them to instance properties.

tagged: static property series part2 refactor consequences testing

Link: https://markbakeruk.net/2018/04/03/discharging-static-2/

QaFoo Blog:
Refactoring Singleton Usage to get Testable Code
Jul 11, 2017 @ 17:22:07

The QaFoo.com blog has a new post sharing a helpful hint on refactoring singletons to make them more testable. Singletons and notoriously difficult to test due to how it can potentially return an unexpected version of an object.

So your code base is littered with singletons and using them? Don't worry, you can start refactoring them out of your code base class by class and introduce increased testability at every step. This strategy is very simple to implement and the probability of breaking your code is very low, especially when you are becoming more experienced with this technique.

They give an example of a service class that uses a singleton to get an instance of the Solarium_Client class via a static method call. They show how to refactor this out into a separate method and then use the "lazy initialization" pattern to only use the singleton if the property isn't already defined. This then allows you to use a setter to inject your own client during testing (a mock most likely).

tagged: refactor testing unittest mock singleton property lazy initialization

Link: https://qafoo.com/blog/107_refactoring_singletons_testability.html

PHPBuilder.com:
Using Dependency Injection in PHP
Mar 03, 2017 @ 16:05:37

The PHPBuilder.com site has posted a tutorial talking about dependency injection in PHP applications covering not only the use of dependency injection (DI) containers but also constructor, setter, property and reflection based injection methods.

Dependency injection is a software design pattern that implements the inversion of a control concept for resolving dependencies. According to this concept, a class should not configure its dependencies statically, but should be configured from the outside.

A dependency is an object that can be used (a service) and an injection is the passing of a dependency to a dependent object (a client) that would use it. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

The tutorial starts out with a simple example of a set of classes that depend on each other through the creation of internal objects. They then show how the different types of dependency injection can help reduce these dependencies with brief descriptions and sample code for each. The final example, a dependency injection container, gives a quick example but also links to several package options you could pull into your application including Pimple, Aura.Di and PHP-DI.

tagged: dependency injection tutorial introduction setter constructor container property

Link: http://www.phpbuilder.com/articles/application-architecture/design/using-dependency-injection-in-php.html

Freek Van der Herten:
Simplifying presenters in Laravel
Sep 20, 2016 @ 14:32:17

Freek Van der Herten has a quick post to his site with a tip about simplifying presenters in your Laravel based application. The "presenters" here are in relation to this package and how it helps with the output of the application.

In the Laravel template that we use to kickstart all our client projects at Spatie, I recently changed the way we handle presenters. Instead of using Jeffrey Way’s popular presenter package we now use simple traits. In this post I want to give some background on that change.

He gives a quick "crash course" on presenters for those not familiar with the concept and how it helps to keep view logic out of places like models and controllers. He briefly describes a presenter class that would return the "first name + last name" combination and what the code could look like. Then it's just a matter of using that trait (the class mentioned just before this) and a new magic property is defined to use in the view.

tagged: laravel presenter view logic property example user name

Link: https://murze.be/2016/09/simplifying-presenters-laravel/

Giorgio Sironi:
Property-based testing primer
Jun 19, 2015 @ 17:15:29

Giorgio Sironi has a new post to his site today talking about a method (and tool) around a different sort of testing practice: property-based testing. The difference is that, instead of hard-coding values and evaluating them post-processing, you're generating random values and ensuring they match against a set of properties, not values.

I'm a great advocate of automated testing and of finding out your code does not work on your machine, 30 seconds after having written it, instead of in production after it has caused a monetary loss and some repair work to be performed. [...] However, classic test suites written with xUnit and BDD styles have some scaling problems they hit when you want to exercise more than some happy paths. [...] Property-based testing is an approach to testing coming from the functional programming world.

He helps to make the point a bit more clear with an example of testing the "sort" function and its results. He talks about how to test it using normal data, empty data, etc. but notes that this kind of testing can become "boring and error-prone". Instead he proposes the property-based testing of the results. He generates random values to feed into the method and checks to ensure the results are sorting by comparing them to each other. He expands this with a bit more complex example, showing how to test some DateTime handling and evaluating the result with logic in a closure. To help make this kind of testing easier, he's created a library (Eris) that extends PHPUnit and provides the methods seen in his examples.

tagged: property testing unittest phpunit extension random datetime sort eris

Link: http://www.giorgiosironi.com/2015/06/property-based-testing-primer.html

Marc Morera:
Behat and Data-test
Apr 27, 2015 @ 14:55:08

In a new post Marc Morera makes a suggestion for a testing practice to add to the use of the popular BDD PHP testing framework Behat - a "data-test" option to help with decoupling the tests from implementation.

Tests should be as robust as possible. I think you will agree with me with that phrase. If your tests are too coupled with your implementation, a simple modification of your code will need the modification of your tests, and that’s so annoying, right? [...] My question is… should the frontend of your website be aware of the how your Behat tests are built? In my opinion, nope. Your tests should live in a simple layout on top of your application, emulating some cases and ensuring that your users will be able to do what they should be able to.

He points out the main problem with the current testing methods, mainly that the real issue is in the hard-wiring of the test functionality to the name/id/type of the interface elements. He also brings up the aspect of translations and ensuring that your tests take into account that the text may not always be in English. He also mentions Symfony forms and how they define their own structure and naming, not necessarily what you manually generate. He instead proposes a "data-test" property that could be added to elements both indicating that they're used by the testing process and can help in locating the elements during the testing process.

tagged: behat bdd datatest property markup testing method opinion

Link: http://mmoreram.com/blog/2015/04/25/behat-and-data-test/

Mathias Verraes:
Objects as Contracts for Behaviour
Sep 29, 2014 @ 16:10:33

Mathias Verraes has a new post to his site today with an interesting idea when it comes to handling the architecture of an application: using objects as the contracts for behavior. He suggests that the objects themselves define how other pieces of code should interact with them, not necessarily external services. He illustrates with an invoice and appointment example.

Of course invoices do not pay themselves, but that’s not what an object model is trying to do. An invoice exposes the behaviour of being able to be paid. That ability is in fact essential to what it means to be an invoice. The behaviour is an inherent property of an invoice. If an invoice doesn’t have the ability of being paid, there’s no point in issuing invoices at all. In other words, the contract of an invoice object declares that its interface includes payment as a feature. Its promise to the outside world is that it allows an outsider to pay for it. Encapsulation of state and behaviour is the core idea behind objects.

He wonders why, if this is more true to the "object-oriented programming" ideals, the idea of encapsulating procedural code as objects is so widespread. He suggests a lack of education on the subject or maybe even confusion from spoken languages themselves.

tagged: objectoriented programming oop contract expose behavior property

Link: http://verraes.net/2014/09/objects-as-contracts-for-behaviour/


Trending Topics: