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

TheCodingMachine.io:
Safe PHP - Throwing Exceptions Instead of Returning False
Sep 27, 2018 @ 16:47:44

On TheCodingMachine.io there's a tutorial posted by David Négrier covering an interesting idea when handling "falseness" in your PHP application - throwing exceptions rather than returning false. In this case, he introduces the "safe" library to help make this easier.

At TheCodingMachine, we are huge fans of PHPStan. PHPStan is an open-source static analysis tool for your PHP code. [...] PHPStan has this notion of "levels" and we strive on each of our projects to reach "level 7" (the maximum level). But PHPStan is constantly improving, and reaching level 7 becomes harder and harder as the tool becomes more strict (this is a good thing!).

The post includes an example of this increasing strictness, showing how a more recent check looks at a file_get_contents call and ensures all possible return values are evaluated (it returns false when it errors). They refactor the code example to more correctly check for this, but losing some of the "expressiveness". The tutorial then spends some time talking about the history of PHP and why things return false rather than throw exceptions on error. It covers some of the basics of how the safe library works and a PHPStan extension that can help find places that need to be wrapped by "safe" to throw exceptions when false is returned.

tagged: safephp library exception false return value tutorial package

Link: https://thecodingmachine.io/introducing-safe-php

Robert Basic:
Mockery return values based on arguments
Dec 13, 2017 @ 21:13:55

Robert Basic has a new post to his site where he shows how to use the Mockery unit testing too to return different values for different arguments. Fortunately there's something already built into the tool to help handle this.

Sometimes when working with Mockery mock objects, we want to tell a mocked method to return different values for different arguments. It is a rare occasion when I need this feature, but every time I need it, I’m happy it’s there.

The feature that allows us to return different values based on arguments is the andReturnUsing Mockery method, which takes a closure as an argument.

He includes examples of the use of this andReturnUsing method in mocks and showing that there's more than one way to accomplish the same kind of goal. While this is a useful method to use when needed he points out that refactoring the code under test is probably a better way to go instead.

tagged: mockery unittest arguments return value tutorial

Link: https://robertbasic.com/blog/mockery-return-values-based-on-arguments/

Paul Jones:
Controllers and Domain Exceptions
May 24, 2017 @ 14:19:52

In a new post to his site Paul Jones shares a conversation he had about handling domain exceptions in controllers and if it was a good practice or not.

A few months ago I had a great email conversation with a correspondent about how to handle business logic exceptions in his controller code. [...] If you find yourself in this situation, the first question to ask yourself is, “Why am I handling domain exceptions in my user interface code?” (Remember: Model-View-Controller and Action-Domain-Responder are user interface patterns; in this case, the user interface is composed of an HTTP request and response.) Domain exceptions should be handled by the domain logic in a domain-appropriate fashion.

He shares the original email (shortened) where they asked their question and outlined their current situation and setup. He points out that the point the other person made about not feeling right to thrown domain exceptions and having the controller handle them is a good path to follow but to take it even further. He suggests modifying the response to the domain logic to be a "domain payload" instead of an exception and then have the controller use that (getting its status) to determine how to proceed. This can prevent the need to catch random exceptions and provides more consistency to the overall flow.

tagged: domain exception controller payload question return tutorial

Link: http://paul-m-jones.com/archives/6608

QaFoo.com:
Never Use null
May 03, 2016 @ 18:07:32

On the QaFoo.com blog they've made a recommendation in their latest post - they suggest that you never use null.

When doing code reviews together with our customers we see a pattern regularly which I consider problematic in multiple regards – the usage of null as a valid property or return value. We can do better than this.

Let's go into common use cases first and then discuss how we can improve the code to make it more resilient against errors and make it simpler to use. Most issues highlighted are especially problematic when others are using your source code. As long as you are the only user (which hopefully is not the case) those patterns might be fine.

They talk about some of the most common uses they see for using null in PHP applications including setters for class properties (injection). They point out that in PHP 7 a missing value on a property would result in a Fatal error and make the functionality harder to test overall. They suggest that all required dependencies be injected on object construction instead, making it easier to know the current state of the object on testing. They also talk some about using null as a return value, how it could make debugging difficult and a solution that could make more sense - throwing an exception instead.

tagged: never use null return value injection setter solution suggestion debugging

Link: https://qafoo.com/blog/083_never_use_null.html

QaFoo:
Testing Effects of Commands With Phake::capture()
Mar 11, 2016 @ 15:15:15

On the QaFoo blog they've posted an article sharing a quick testing tip when using Phake to test APIs where the calls don't return any data.

Today I want to share a simple trick for the excellent Mocking library Phake (I wrote about it before) when testing state on APIs that don't return values.

Testing becomes harder when you are using command / query separation in your code and service operations don't return values anymore. If your command method creates objects and passes them down the stack, then you usually want to make assertions on the nature of the changes.

He gives an example of a class that creates an Order object and saves it but doesn't return a value. He shows how to update this with Phake in the test to capture and verify that the calls are correctly made and the number of products on the order is correct.

tagged: phake capture tutorial example unittest return value

Link: https://qafoo.com/blog/078_phake_capture.html

PHP Town Hall Podcast:
Episode 40: Return of the Ferrara
Apr 23, 2015 @ 14:02:26

The PHP Town Hall podcast has posted a new episode today with the Return of the Ferrara. Hosts Ben Edmunds and Phil Sturgeon are joined once again by guest Anthony Ferrara to talk about, among other things, scalar type hints.

Regular guest Anthony Ferrara joins us “in the studio” to talk about the new version of his scalar type hints, which since recording - a f**king month ago - has been accepted for PHP 7. We thought it would be good to have a bit of a chat about the feature, the nonsense that surrounded it and a bunch of other random internals and PHP 7 related blathering.

You can catch this latest episode in a few different ways, either through the in-page audio player, by downloading the mp3 or through the video recording of the live session. If you enjoy the show, be sure to subscribe to their feed too.

tagged: phptownhall podcast ep40 return anthonyferrara scalartypehints php7 interview

Link: http://phptownhall.com/blog/2015/03/20/episode-40-ferrara-scalar-type-hints/

Mathias Noback:
Some questions about the command bus
Jan 12, 2015 @ 15:46:46

Mathias Noback has continued his series looking at the use of command busses in PHP applications. In this third part of his series, he answers some questions that have been asked by his own readers.

So far we've had three posts in this series about commands, events and their corresponding buses and handlers: a wave of command buses, responsibilities of the command bus, from commands to events. Now I'd like to take the time to answer some of the very interesting questions that by readers.

He answers questions about:

  • The difference between commands and events
  • Disadvantages of using a command bus
  • The command as constructor argument
  • How to return a value from the command bus
  • Could commands handle themselves?

Each question comes with a portion of the question from the original author, an explanation and some code where needed to illustrate his point.

tagged: commandbus question answer reader events disadvantages return handling

Link: http://php-and-symfony.matthiasnoback.nl/2015/01/some-questions-about-the-command-bus/

Matthew Weier O'Phinney:
Deployment with Zend Server (Part 5 of 8)
Sep 10, 2014 @ 18:40:49

Matthew Weier O'Phinney has posted the latest in his "deployment with Zend Server" tips today, part five of eight. In this latest post he talks about setting the status of a job.

This is the fifth in a series of eight posts detailing tips on deploying to Zend Server. The previous post in the series detailed how to secure your Job Queue job scripts. Today, I'm sharing some best practices around writing job scripts, particularly around how to indicate execution status.

When he talks about the "status" of a job he's referencing the return code that's provided back to the executing script sharing the pass/fail status of its execution. He shows how to use the ZendJobQueue object and the setCurrentJobStatus to return a constant, either "FAILED" or "OK". He shows how to use it in an isolated example, outputting the results back as a plain text message that can be found in the "Output" tab of the job.

tagged: zendserver deployment tips series part5 return status failed ok

Link: https://mwop.net/blog/2014-09-09-zend-server-deployment-part-5.html

Federico Cargnelutti:
TDD: Checking the return value of a Stub
Apr 16, 2014 @ 15:25:15

Federico Cargnelutti has a helpful post to his site today for the unit testing/TDD crowd about checking the retuned value from a stub of an object in your tests. He's using the built-in mocking framework here, not something like Mockery.

State verification is used to ensure that after a method is run, the returned value of the SUT is as expected. Of course, you may need to use Stubs on a test double or a real object to tell the object to return a value in response to a given message. [...] In PHP, for example, you dynamically type the return value within the body of the method. This means that PHP mocking libraries cannot check the type of the return value and provide guarantees about what is being verified. This leads to the awkward situation where a refactoring may change the SUT behaviour and leave a stub broken but with passing tests.

He gives an example of a few classes - a Presenter and Collaborator - and a test that mocks out the Collaborator instance, calling a "getStories" method on it. He shows a situation where all tests pass in the initial version, but after some changes to the return type, a test that should fail doesn't. His solution for the issue revolves around DocBlock annotations and the Return Value instead of the built-in mock object return method.

tagged: tdd unittest return value stub passing test returnvalue mock

Link: http://blog.fedecarg.com/2014/04/15/checking-the-return-value-of-a-stub/

Derick Rethans:
DateTimeImmutable
Feb 26, 2014 @ 16:26:45

In his latest post Derick Rethans (knower of all things date and time) talks about the DateTimeImmutable functionality. It has been added into the PHP 5.5 releases and provides the same DateTime functionality but removes the ability for modification (mutability).

The first time that my improved DateTime support made its way into PHP was officially in PHP 5.1, although the more advanced features such as the DateTime class only made it appearance in PHP 5.2. Since its introduction the DateTime class implementation suffered from one design mistake - arguably not something that even an RFC would have highlighted. [...] This mutability property that all modifying methods of the DateTime class have is highly annoying, and something that I would now rather remove. But of course we cannot as that would break backwards compatibility. So in PHP 5.5, after a few stumbles, I finally managed to rectify this.

He includes some code examples showing the current DateTime object's mutability (via the "modify" function) and the new immutable handling. This new handling doesn't update the current object but instead returns the modified object, leaving the initial one intact. You can find out more about this new object in the PHP manual.

tagged: datetime datetimeimmutable mutability return object php55

Link: http://derickrethans.nl/immutable-datetime.html


Trending Topics: