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

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

TutsPlus.com:
Object-Oriented PHP With Classes and Objects
Dec 04, 2018 @ 19:07:40

On the TutsPlus.com site, they've posted a tutorial for those wanting to get started with object-oriented programming (OOP) in PHP. In this introductory article they cover the basics of objects, classes and several over OOP-related topics.

In this article, we're going to explore the basics of object-oriented programming in PHP. We'll start with an introduction to classes and objects, and we'll discuss a couple of advanced concepts like inheritance and polymorphism in the latter half of this article.

The tutorial starts with the basics, explaining some of the key terms involved in OOP and how they can be manipulated. From there they include code examples of classes, making instances of them as objects and accessing properties and methods. With those basics out of the way, they move on to more advanced topics: encapsulation, inheritance and the basics of polymorphism.

tagged: oop objectoriented programming tutorial beginner class object

Link: https://code.tutsplus.com/tutorials/basics-of-object-oriented-programming-in-php--cms-31910

Matthias Noback:
Test-driving repository classes - Part 2: Storing and retrieving entities
Oct 08, 2018 @ 19:44:04

Matthias Noback has continued his series of tutorials covering various uses of the Repository design pattern. This is the second part of the series and picks up where part one left of, showing the handling of entities in the repository, performing the usual CRUD operations.

In part 1 of this short series (it's going to end with this article) we covered how you can test-drive the queries in a repository class. Returning query results is only part of the job of a repository though. The other part is to store objects (entities), retrieve them using something like a save() and a getById() method, and possibly delete them. Some people will implement these two jobs in one repository class, some like to use two or even many repositories for this. When you have a separate write and read model (CQRS), the read model repositories will have the querying functionality (e.g. find me all the active products), the write model repositories will have the store/retrieve/delete functionality.

In particular if you write your own mapping code (like I've been doing a lot recently), you need to write some extra tests to verify that the persistence-related activities of your repository function correctly.

He starts with the test cases for the functionality (following the test-drive design mentality) and talks about the expected behavior of the various entity and repository methods. He includes the code for these tests covering state changes, handling child entities, deleting entities, and working with ports/adapters.

tagged: entities repository class tutorial series part2 test

Link: https://matthiasnoback.nl/2018/10/test-driving-repository-classes-part-2-storing-and-retrieving-entities/

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

Matthias Noback:
Final classes by default, why?
Sep 12, 2018 @ 17:08:54

In this post to his site Matthias Noback makes the argument that, during your normal development, classes should be final by default and only changed if there's a need to extend them.

I recently wrote about when to add an interface to a class. After explaining good reasons for adding an interface, I claim that if none of those reasons apply in your situation, you should just use a class and declare it "final".

[...] For a couple of years now I've been using the final keyword everywhere (thanks to Marco Pivetta for <a href="https://ocramius.github.io/blog/when-to-declare-classes-final/>getting me on track!). When I see a class that's not final, it feels to me like it's a very vulnerable class. Its internals are out in the open; people can do with it what they want, not only what its creator has imagined.

Still, I also remember my initial resistance to adding final to every class definition, and I often have to defend myself during workshops, so I thought it would help if I explained all about it here.

He starts off by talking about the alternative - non-final classes - and some of the issues that can come with it (and class extension). He makes the suggestion that "replacing is better than overriding" and creates less complexity overall. He also answers a question about the use of the "Template Method" design pattern that would allow for improvement from base "skeleton" logic designed to be extended. He covers "composition over inheritance", the use case of extension and how "final" is a better direction.

tagged: final class exposure extension opinion override template composition

Link: https://matthiasnoback.nl/2018/09/final-classes-by-default-why/

Matthias Noback:
When to add an interface to a class
Aug 28, 2018 @ 14:12:04

Matthias Noback has a tutorial posted to his site sharing his thoughts on when adding an interface to a class is useful. Here he's talking about using interfaces as a structure for your application, making it easier to understand and more structured.

I'm currently revising my book "Principles of Package Design". It covers lots of design principles, like the SOLID principles and the lesser known Package (or Component) Design Principles. When discussing these principles in the book, I regularly encourage the reader to add more interfaces to their classes, to make the overall design of the package or application more flexible. However, not every class needs an interface, and not every interface makes sense. I thought it would be useful to enumerate some good reasons for adding an interface to a class. At the end of this post I'll make sure to mention a few good reasons for not adding an interface too.

He then offers five suggestions of cases where an interface makes sense:

  • If not all public methods are meant to be used by regular clients
  • If the class uses I/O
  • If the class depends on third-party code
  • If you want to introduce an abstraction for multiple specific things
  • If you foresee that the user wants to replace part of the object hierarchy

For each item in the list he provides a summary of the suggestion and some code snippets to back it up. He ends the post with a recommendation about how to handle most other situations where you think an interface might be useful: use a "final" class instead.

tagged: interface class opinion structure top5 class tutorial

Link: https://matthiasnoback.nl/2018/08/when-to-add-an-interface-to-a-class/

Matthias Noback:
When to add an interface to a class
Aug 28, 2018 @ 14:12:04

Matthias Noback has a tutorial posted to his site sharing his thoughts on when adding an interface to a class is useful. Here he's talking about using interfaces as a structure for your application, making it easier to understand and more structured.

I'm currently revising my book "Principles of Package Design". It covers lots of design principles, like the SOLID principles and the lesser known Package (or Component) Design Principles. When discussing these principles in the book, I regularly encourage the reader to add more interfaces to their classes, to make the overall design of the package or application more flexible. However, not every class needs an interface, and not every interface makes sense. I thought it would be useful to enumerate some good reasons for adding an interface to a class. At the end of this post I'll make sure to mention a few good reasons for not adding an interface too.

He then offers five suggestions of cases where an interface makes sense:

  • If not all public methods are meant to be used by regular clients
  • If the class uses I/O
  • If the class depends on third-party code
  • If you want to introduce an abstraction for multiple specific things
  • If you foresee that the user wants to replace part of the object hierarchy

For each item in the list he provides a summary of the suggestion and some code snippets to back it up. He ends the post with a recommendation about how to handle most other situations where you think an interface might be useful: use a "final" class instead.

tagged: interface class opinion structure top5 class tutorial

Link: https://matthiasnoback.nl/2018/08/when-to-add-an-interface-to-a-class/

Larry Garfield:
PHP: Never type hint on arrays
Jul 30, 2018 @ 17:05:48

In a new post Larry Garfield makes an interesting suggestion related to the use of arrays in PHP. He suggests that you should never type hint arrays in your method definitions.

Let's be controversial: In modern PHP, you should never type-hint an array. Before you start throwing tomatoes, hear me out.

PHP allows you to specify the type of a function/method parameter or return value. These return values can be any legal PHP type. [...] PHP has a data type that it calls array, although it's not really an array as any other language would define it. [...] And you should almost never use array as a type hint. Why? Because there's always a better, more generic option.

He starts off talking about the use case where arrays are used as a "single complex value" and how,. more often than not, a class is actually a better option. He then covers the other main use of arrays: as an ordered sequence of values. To replace this he recommends a more structured collection that can apply some logic to its contents. With these other options out of the way, he then talks about what arrays are actually useful for and some other potential typehints to allow arrays and other potential inputs. He ends the post talking about array operations included in PHP and how, with a minimal amount of effort, they could be reproduced with simple methods for use on actual collection instances instead.

tagged: typehint array options class collection opinion

Link: https://steemit.com/php/@crell/php-never-type-hint-on-arrays

Matt Sparks:
PHP Reflection
Jul 02, 2018 @ 17:42:41

Matt Sparks has posted a tutorial to his site introducing one of the more powerful but often misunderstood parts of the PHP language: its Reflection functionality.

Beginning work on the Analyze PHP framework, specifically the container, brought reflection to my awareness. Before that I had maybe heard the term, but I definitely hadn’t used it intentionally. Although it sounds like a scary computer science concept, it’s not. It’s actually quite simple:

Reflection is the ability of a computer program to examine, introspect, and modify its own structure… That’s it.

He starts the tutorial by introducing some of the basics concepts behind reflection in PHP and what it has to offer. He then shares some code examples of it in action getting class properties and getting the constructor. He also shows the use of other built-in PHP functions getting the class methods and the class name.

tagged: reflection tutorial introduction class method name properties constructor

Link: https://developmentmatt.com/php-reflection/

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


Trending Topics: