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

Tomas Votruba:
Function create_function() is Deprecated in PHP 7.2 - How to Migrate?
Dec 18, 2018 @ 15:34:16

In this post to his site Tomas Votruba covers the create_function function, its deprecation in PHP 7.2 and how to refactor your code to remove it.

If there would be "Miss Deprecation of PHP 7.2", create_function() would definitely win. They can be very complex, tricky and very hard convert to PHP code. Moreover without tests.

Do you have over 5 create_function() pieces in your code? Let's see how to migrate them.

He starts by talking about why it's being deprecated (it's essentially an eval) and some examples of how it could be used to execute code. He then goes through several usage examples and shows how to refactor them into anonymous functions. In his examples he uses a mix of regular code conversions and a sort of hybrid using strings and code to replace the string (probably) used previously with create_function.

tagged: createfunction function deprecation anonymous tutorial refactor

Link: https://www.tomasvotruba.cz/blog/2018/12/17/function-create-function-is-deprecated-in-php-72-how-to-migrate/

Matthew Weier O'Phinney:
Creating Exception types on-the-fly in modern PHP
Dec 07, 2018 @ 17:44:03

Matthew Weier O'Phinney has posted a tutorial to his site sharing a method he's found for creating Exception types dynamically allowing you to create a system that can still be caught by normal means but is more flexible than hard-coded exceptions.

We pioneered a pattern for exception handling for Zend Framework back as we initially began development on version 2 around seven years ago. The pattern looks like this: we would create a marker ExceptionInterface for each package. [Then] we would extend SPL exceptions and implement the package marker interface when doing so.

What this gave users was the ability to catch in three ways. [...] This kind of granularity is really nice to work with. [...] So, what happens when you're writing a one-off implementation of something that is expected to throw an exception matching one of these interfaces?

Why, use an anonymous class, of course!

He includes an example of putting this approach to work, using a throw call along with a dynamic (anonymous) class to extend the required class and implement the associated interface. In his example he creates a dynamic exception for handling a "not found" type of exception.

tagged: exception dynamic tutorial anonymous class custom

Link: https://mwop.net/blog/2018-12-05-on-the-fly-exceptions.html

Larry Garfield:
Don't use Mocking libraries
Sep 21, 2018 @ 16:02:10

Larry Garfield has written up a post with a somewhat controversial headline, especially for anyone that's done any kind of unit testing on a larger codebase. His suggestion is to no use mocking libraries and some other techniques that can replace them.

I am all for testing. [...] There's a lot of opinions on what constitutes a "good" test, of course, and much is subjective to the type of code you're working on. However, since the release of PHP 7 I've found that while writing tests... I am never using a mocking library. In fact, I'm going to go as far and say that you should never use a mocking library in PHP 7.

Before all of you gasp, clutch your pearls, and send ninja hit squads after me, let me justify that position.

He starts off by defining what a "mock" is a more general sense and then, more specifically, how mocking libraries are mostly implemented in PHP. He covers the DSL (domain specific language) knowledge that's required to use most of them and how something already included in PHP 7 - anonymous classes - could be a viable alternative. He goes on to show examples of using this method rather than a mock for simple object handling and even recommends making an actual class (just for testing) if the need is there. He ends the post talking about the "upper bounds" of when this might not be as useful and how this can actually be good (using it as an indicator that you need to refactor the main code to simplify).

tagged: mocking mock library testing unittest opinion anonymous class

Link: https://steemit.com/php/@crell/don-t-use-mocking-libraries

Zend Blog:
Zend Framework - ACLs for users with multiple roles
Jul 06, 2018 @ 17:44:25

On the Zend Blog there's a new tutorial posted that covers the situation where a user has multiple roles and you're using ACLs (access control lists). The post shows how to accomplish this with the ZendAcl component of the Zend Framework.

After covering the essentials of the ZendPermissionsAcl component (Access Control unit, Cross Cutting Concerns module, in the Zend Framework Advanced course), many students have approached me to ask, “what happens if a user has multiple roles?”

In this article I discuss the “traditional” way of handling a user who has multiple roles, and then lay out an easy approach which I simply call Mr. X.

The tutorial starts with a bit of a refresher on the use of the ZendAcl component to define the list of roles and resources (and relating the two). It also covers the "everyone" (anonymous) role and adding that into the mix. The "one user, multiple roles" issue is then solved with a multiCheck function that can verify multiple roles at once. Finally it talks about "Mr. X" and how to add that to all users, assuming that they will have the groups/roles information we need.

tagged: zend zendframework acl multiple role tutorial anonymous

Link: http://blog.zend.com/2018/07/05/zend-framework-access-control-lists/#.Wz9wv9hKjUY

Larry Garfield:
PHP: Use associative arrays basically never
Jul 02, 2018 @ 15:50:59

In a new post Larry Garfield suggests and interesting approach to arrays in PHP: stop using associative arrays (or at least "basically never").

The other day I was working on some sample code to test out an idea that involved an object with an internal nested array. This is a pretty common pattern in PHP: You have some simple one-off internal data structure so you make an informal struct using PHP associative arrays. Maybe you document it in a docblock, or maybe you're a lazy jerk and you don't. (Fight me!) But really, who bothers with defining a class for something that simple?

But that got me wondering, is that common pattern really, you know, good? Are objects actually more expensive or harder to work with than arrays? Or, more to the point, is that true today on PHP 7 given all the optimizations that have happened over the years compared with the bad old days of PHP 4?

So like any good scientist I decided to test it: What I found will shock you!

He starts by describing his test environment (a local environment, not a cloud one) and the code for his baseline tests. The code generates an array of one million items where each item is an associative array of an integer/string combo. He wants to see what kind of memory consumption is involved in the creation and processing of this data set via sorting. His second test evaluated the serialization size (again, code provided) again checking the memory consumption. He shares the results of these tests and then moves on to similar tests on:

  • stdClass instances
  • objects with public properties
  • objects with private properties
  • anonymous classes

The post ends with a summary showing the results of all tests side-by-side with some interesting results (but you'll have to check out the post for yourself if you want to see those).

tagged: associative array never benchmark object class anonymous results statistics

Link: https://steemit.com/php/@crell/php-use-associative-arrays-basically-never

Mark Baker:
Using PHP Anonymous Classes as Package Private Classes
Jun 26, 2018 @ 20:09:36

Mark Baker has a post to his site about some of the interesting things you can do with anonymous classes, focusing on their use outside of testing (as he has in previous articles).

I’ve written before about the benefits of using PHP’s Anonymous Classes for test doubles; but Anonymous Classes also have potential usecases within production code as well. In this article I’m going to describe one such usecase that can be particularly useful within libraries, and that is replicating the access of Package Private (in Java), or Protected Internal Classes (as per C#).

He briefly explains what the package private/protected internal classes functionality entails before getting into his own use of the method with the PHPExcel/PHPSpreadsheet packages. He defines how he thinks the system should be structured and the isolation the anonymous classes would provide (without having to make whole separate classes just for that). He creates a class that has all public methods accessible but cannot be instantiated from outside the library. He shares some example code to illustrate his point, walking through each step to show what it's doing and how.

tagged: anonymous class package private class tutorial phpexcel

Link: https://markbakeruk.net/2018/06/25/using-php-anonymous-classes-as-package-private-classes/

Tomas Votruba:
How to Turn Mocks from Nightmare to Solid Kiss Tests
Jun 13, 2018 @ 17:36:48

In a new post to his site Tomas Votruba shows you how to make your unit test mocks better with an easier and clearer way to use them. This simplification makes use of something PHP itself is already able to do: create anonymous classes.

At the time being, there is only 1 post about anonymous classes in tests (thanks to Matthieu!). Compared to that, there are many PHP tool made just for mocking: Prophecy, Mockery, PHPUnit native mocks, Mockista and so on. If you're a developer who uses one of them, knows that he needs to add proper annotations to make autocomplete work, has the PHPStom plugin that fixes bugs in this autocomplete and it works well for you, just stop reading.

This post is for developers who struggle with mocking and have a feeling, that they're doing something wrong.

He starts with an example of a test that creates a mock for an external request to the Heroku service using PHPUnit's mocking tools. He points out that this requires extra knowledge of the mocking methods and functionality to accomplish, potentially making it difficult to understand for those new to the tool. He then shares a refactor of the same test, this time making use of an anonymous class to mock out the needed findByCategoryId method and return a response. He ends the post pointing out that, as a side effect of this refactoring (and other interface refactoring) you'll create more SOLID code and it can help make it easier to maintain in the future.

tagged: tutorial mock unittest test anonymous class tool

Link: https://www.tomasvotruba.cz/blog/2018/06/11/how-to-turn-mocks-from-nightmare-to-solid-kiss-tests/

Mark Baker:
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 4)
Jan 23, 2018 @ 16:21:14

Mark Baker has returned with a new part of his series looking at the use of anonymous classes and closures as an alternative to the typical test mocking functionality. In this latest part (part four) he talks more about the "SpyMaster" class created in the previous article and how it can be refactored to provide the spies with a "mission".

In a prior article in this series, I described the use of a SpyMaster Class to create proxy spies as anonymous classes, that allow external visibility (and potentially update) of protected and private properties within an object. The same basic principle of a spy can also be used to create a proxy that gives us access to execute the private and protected methods of an object.

[...] Unlike the original SpyMaster that I wrote about last July, we’re going to take a slightly different approach here, providing our spies with a “mission”.

He first shares the code for the old class and covers why it was useful. He then moves on to the refactor, showing how it defines the "mission" (what to mock) and an "invoker" that helps with the actual execution. He gives an example of this new class in use, performing an "infiltration" on a sample object and calling previously protected methods directly.

tagged: closure anonymous class alternative mock tutorial part4 series

Link: https://markbakeruk.net/2018/01/23/closures-anonymous-classes-and-an-alternative-approach-to-test-mocking-part-4/

Mark Baker:
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 3)
Sep 19, 2017 @ 16:58:39

Mark Baker has posted the third part of his series looking at an alternative way to handle mocking in the tests for your PHP application. In this latest part of the series he shows how to modify one of PHPUnit's own mocking examples to use an anonymous class.

I have heard people say that you shouldn’t test abstract classes or traits, only the concrete classes that implement or use them. I don’t follow that approach: unit testing is all about testing in isolation from anything that might affect those tests. Testing a concrete class that implements an abstract one, or uses a trait, means that the abstract class or trait is no longer fully isolated, but is being tested within the scope of the whole of that concrete class. We should still always test concrete classes as well; but we should also test the abstract classes and traits as individual units.

So just how do we test something that cannot be instantiated on its own?

He shares one tactic that some developers use - a class designed only for testing - but suggests that this "pollutes" the codebase. Instead he shows how to replace mocking for traits and abstract classes with an anonymous class that's more "disposable". He also shows how to modify this approach to handle calling protected methods in the class the anonymous class extends.

tagged: closure anonymous class alternative mock tutorial part3 series

Link: https://markbakeruk.net/2017/09/18/closures-anonymous-classes-and-an-alternative-approach-to-test-mocking-part-3/

Mark Baker:
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 2)
Aug 11, 2017 @ 15:44:19

Mark Baker has posted the second part of his series covering the use of closures and anonymous classes as an alternative approach to mocking in your unit tests. In part one he introduced some of the basic concepts behind their use and in this latest post he focuses on "different approach to using an Anonymous Class to verify the values of object properties".

The last time I posted here, I was writing about Anonymous Functions and how they can be bound to any object (or class) to execute as though they are a method within the scope of that class (Closure Binding as an alternative to “use” variables); and in the first article in this series, I looked at using a Closure to access private and protected properties of an object.

I was going to write this particular article about using simple Anonymous Classes to create test doubles for Unit Testing – and may well return to that topic in a future article in the series – but Matt Brunt has written a good post on that topic already, so instead I’m going to focus on a different approach to using an Anonymous Class to verify the values of object properties that we otherwise couldn’t see directly when testing a class.

He goes on to talk about some ideas from the Java ecosystem around nested classes and scoping. He then shows how, with closure binding, the same kind of effect can be created in PHP testing. He includes the code for an example of a class that coverts distance measurements. He then introduces his "SpyMaster" utility class that "infiltrates" the class under test and attaches the closure providing the needed point for testing. He finishes up the post talking about this functionality and how the technique can be used in many places, not just testing class constructors.

tagged: closure anonymous class alternative mock tutorial part2 series

Link: https://markbakeruk.net/2017/07/30/closures-anonymous-classes-and-an-alternative-approach-to-test-mocking-part-2/


Trending Topics: