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

Russell Walker:
Is Best Practice Actually Poor Practice? Dependency Injection, Type Hinting, and Uni
Apr 05, 2017 @ 13:26:03

Russell Walker has a post to his site sharing his thoughts defending dependency injection, type hinting and unit testing against some of the common objections.

I've recently been in discussion with a colleague who thinks that dependency injection (DI) is over-used and, in cases where the dependency is a concrete class, unnecessary (in the latter case, he advocates simply creating new objects on the fly).

[...] In my opinion, this line of thinking is misguided, but he sent through some links to pages that he felt supported his point of view (including Tony Marston's rant on DI, and the Laravel documentation about 'facades' - which are actually used as an alternative syntax for the service locator [anti-]pattern). I genuinely wanted to understand the reasoning behind his point of view, as it flies in the face of just about everything I have ever read regarding best practice in PHP development. After reading those resources he sent though, I began to notice some misconceptions about what unit testing actually is, as well as confusion about the difference between code that is "strongly typed" (usually good) and "tightly coupled" (usually bad), and also a tendency to blame the wrong thing when problems arise.

He then breaks the rest of the post down into a few of the common objections and makes an attempt to set the record straight:

  • Not All Automated Tests Are Unit Tests
  • Using Mocks to Test in Isolation
  • What, Never Ever Create Objects on the Fly?
  • What About Those Laravel Facades?
  • Hidden Dependencies and Other Dangers
  • Strongly Typed is not Tightly Coupled

He ends the post with "another reason" that there could be issues with developers dismissing best practices in their development - a misunderstanding of the principle and how to correctly implement it.

tagged: bestpractice dependencyinjection typehint unittest opinion

Link: http://russellscottwalker.blogspot.co.uk/2017/03/is-best-practice-actually-poor-practice.html

Evert Pot:
PHP's callable typehint too loose?
May 07, 2015 @ 10:19:56

In his latest post Evert Pot wonders if the current implementation of the "Callable" type in PHP is too loose when it comes to what it will accept as a valid callable resource.

PHP got support for closures in version 5.3, and in PHP 5.4 we got support for a callable typehint. [...] All these little changes make it feel more comfortable to apply functional programming concepts to PHP, but occasionally we need to drop back to using less aesthetically pleasing code.

In his examples of "less aesthetically pleasing code" he shows a few different methods that work that aren't the typical closure or object arguments (like passing in an array of object+method name). He also shows an interesting option where you can use a string with a static method call (ex: "MyClass::method") and it will still be accepted. He points out that for this to work correctly in all situations, the call_user_func method should be used, not just calling the input directly.

tagged: callable typehint loose object method array variable iscallable calluserfunc

Link: http://evertpot.com/on-callables-and-closures/

Lately in PHP Podcast #48 - To TDD or Not TDD?
Jun 27, 2014 @ 11:38:37

On the PHPClasses.org site today Manuel Lemos has released the latest episode in their "Lately in PHP" podcast series: Episode #48 - To TDD or Not TDD?.

Lately the debate about whether you should use TDD or not in all software projects all the time has been very intense. [...] They also talked about the upcoming end of life release of PHP 5.3, getting information of parameter type hinting with reflection, using object methods on native data types, security problems of OAuth implementations, and the built-in support of Composer to access password protected repositories.

You can listen to this latest episode either through the in-page audio player, by downloading the mp3 or you can watch the live recording over on the PHPClasses YouTube playlist. A transcription of the recording is also provided as well as links to some of the topics mentioned.

tagged: phpclasses latelyinphp ep48 podcast tdd typehint oauth security composer

Link: http://www.phpclasses.org/blog/post/239-To-TDD-or-Not-TDD--Lately-in-PHP-podcast-episode-48.html

Wojciech Sznapka:
Type Hinting is important
Jun 12, 2014 @ 09:41:51

In his latest post Wojciech Sznapka reminds us that type hinting is important in your PHP applications and can help provide more structure and better overall code practices.

One of my favorite PHP interview questions, is: what is Type Hinting and why it’s important? Putting definition in one sentence, Type Hinting is a way to define type of parameter in function signature and it’s a sine qua non to leverage polymorphism. [...] So given the fact, that Type Hinting is optional and we don’t need to specify types of parameters passed to the method – why bother? Answer is easy: well prepared method signatures defines your model and are part of the “contract” that your code reveals to its consumers. It also prevents many silly errors and keeps codebase clean and coherent.

He talks about the best practices on using type hinting including where to put them (in an interface or base class or child class?) and some of the pros and cons of each. He also points out that some practices around type hinting, like overriding the hint and calling the method with unexpected/variable input, should be avoided (see the L in SOLID).

tagged: typehint importance bestpractice liskov substitution principle solid

Link: http://blog.sznapka.pl/type-hinting-is-important

Lesser-Known "Features" of PHP's OO Model
Jul 22, 2013 @ 12:21:22

On PHPMaster.com there's a new tutorial from Lorna Mitchell about some of the lesser known OOP features that are built in to the PHP language. She talks about things like interface inheritance, private properties and autoloading and type hints.

The vast majority of today’s applications written in PHP are object-oriented, and in general the core OOP concepts are pretty well understood by PHP developers. This article pushes the boundary of your understanding and shows you some tricks, or potential pitfalls depending on your perspective, of OOP in PHP.

Besides the ones mentioned above, she also looks at abstract classes and their use as well as the use of "finally" to handle the cleanup after exceptions.

tagged: features oop model language private inheritance typehint finally

Link: http://phpmaster.com/lesser-known-features-of-phps-oo-model

Tutorial: Type Hinting in PHP
Aug 01, 2012 @ 12:14:35

On the PHPEasy.co.uk site there's a quick new tutorial posted about type hinting in PHP - how to use it and why you should use it in your code.

Type hinting allows you to tell a function which data type to accept for its arguments. When you call a function, if a type hint is present, the argument passed will be checked to make sure it is of the type specified. If a function has control over what it accepts as an argument, then it is more likely that the code within the function will have the data it needs to perform the task it is intended for.

He includes two code examples - one not using a type hinting on the parameters (assuming the correct arguments) and another forcing the input of the "PrintGuitar" method to be a "Guitar" object instance. You can find out more about type hinting in the PHP manual.

tagged: tutorial typehint example code beginner


James Fuller's Blog:
Enforcing contracts in your PHP functions and methods
Mar 23, 2012 @ 08:37:11

James Fuller has a new post to his blog today about a way you can enforce contracts in your PHP using a combination of type hinting and value checking.

Design by contract is an important concept for controlling what type of input your methods or functions can receive. One of the most dangerous features of PHP is that functions will still execute even when they are missing required arguments, by emitting a warning instead of an error. In this post, I am going to walk through some of the solutions available to deal with this problem.

He shows how to alter a basic function to first use type hinting to catch when a variable is the wrong type (in this case checking for an array and stdClass) which causes a Fatal error and makes the function not execute. He includes sample code for the type/value checking option and also includes a suggestion of using PHPUnit's assertions as another option.

Finally, he introduces the ContractLib tool (from Stuart Herbert) that makes use of closures to enforce checks - his example checks to see if something is a string and that it's not empty.

tagged: enforce contract function exception typehint contractlib


Reuse your closures with functors
Dec 29, 2010 @ 10:50:19

On DZone.com there's a new tutorial from Giorgio Sironi about reusing closures with the help of functors (a special kind of object instancing done in PHP with the help of __invoke).

I like PHP closures and their superset, anomyous functions, as they implement the Command pattern very well when used correctly. However I feel that sometimes they are: difficult to reuse and difficult to force contracts on. [...] What if we wanted instead, a closure which we can instance even more than one time (maybe with different variables), and that we could type hint?

He shows how to make this possible with a functor created using the __invoke magic method of PHP to handle the request to an object like a function. He includes some sample code to show it in action - a basic callback (SquareCallback) and how it compares to calling a normal closure. It also shows something a bit more technical, an "AdderCallback" class that can be defined as a type hint on a function.

tagged: closure functor invoke snippet example callback typehint


OpenSky Blog:
Inheritance in PHP, or why you want to use an Interface or an Abstract class...
Nov 30, 2010 @ 11:09:17

On the OpenSky blog today there's a new post about object oriented development and class structure. More specifically about how you should use interfaces and abstract classes if you want to truly lock down the methods of your classes.

Every class has an interface, every class can be typehinted as a method argument, typehint lets you specify the collaborator requirements. Not every typehint is the same.

He includes an example of how, despite a "BankAccount" type hint, classes for different types of accounts can be created and methods from the parent can be overwritten. To help remedy the situation, he shows a more structured example that uses interfaces/an abstract class to define the BankAccount structure, setting requirements on the child class functionality.

tagged: typehint interface abstract class example structure


Ilia Alshaetsky's Blog:
Type Hinting - Conclusion
Jul 23, 2009 @ 08:27:52

Following up on all of the craziness that was caused by the suggestion of including type hinting into the PHP core, Ilia Alshaetsky recently posted some of his thoughts on how things turned out and where he'll go from here.

Unfortunately, while initial outpouring of support for inclusion of type hinting into PHP 5.3 and 6 was substantial, it all kinda petered out once more people started voting. To be specific, there is a large amount of support for the feature in general, but very few people seem to think it should go into 5.3. [...] That said, at work we will transition to 5.3 soon, probably around 5.3.2/3 time, so I do need a type hinting patch. To that effect I've cleaned up and improved the old patch based on comments from various people, notably Stas and Dmitry (thank guys) and made a copy that I intend to use for work.

He talks about how the patch works - no more virtual types and no casting support. Three things have been changed to make it all work: modification to the parser, added a getTypeHint function, properly parse type hints in the code.

tagged: release patch typehint