Posts tagged with best practices

Method overloading is possible in PHP (sort of)

PHP does not support method overloading. In case you've never heard of method overloading, it means that the language can pick a method based on which parameters you're using to call it. This is possible in many other programming languages like Java, C++.

So, under normal circumstances, you can't do this in PHP:

class Foo
{
   function bar(A $baz)
   {
      ...
   }

   function bar(B $baz)
   {
      ...
   }
}

However, with some clever coding, Adam Wathan made a trait, aptly called Overloadable, that makes method overloading possible. It works by just accepting any parameters using the splat operator and then determining which of the given functions must be called according to the given parameters.

Let's rewrite that example above using the Overloadable trait.

class Foo
{
    use Overloadable;

    function bar(...$arguments)
    {
        return $this->overload($arguments, [
            function (A $baz) {
               $this->functionThatProcessesObjectA($baz);
            },
            function (B $baz) {
               $this->functionThatProcessesObjectB($baz);
            },
        ]);
    }
}

Pretty cool stuff. In a gist on GitHub Adam shares a couple of examples, the source code of the trait and the tests that go along with it. Check it out!

https://gist.github.com/adamwathan/120f5acb69ba84e3fa911437242796c3

Read more

Join 9,500+ smart developers

Every month I share what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

Taking PHP Seriously

Keith Adams, Chief Architect at Slack, gives some background on how PHP is used at his company.

Slack uses PHP for most of its server-side application logic, which is an unusual choice these days. Why did we choose to build a new project in this language? Should you?

Most programmers who have only casually used PHP know two things about it: that it is a bad language, which they would never use if given the choice; and that some of the most extraordinarily successful projects in history use it. This is not quite a contradiction, but it should make us curious. Did Facebook, Wikipedia, Wordpress, Etsy, Baidu, Box, and more recently Slack all succeed in spite of using PHP? Would they all have been better off expressing their application in Ruby? Erlang? Haskell?

https://slack.engineering/taking-php-seriously-cf7a60065329

Read more

When are single-character variable names acceptable?

Generally I don't like to abbreviate variable names. This answer on Quora lists a few situations where an abbreviation is probably ok.

There is a simple (but unsatisfying) answer to all questions of this form: they are acceptable when they would make the code clearer.

This can happen in a few ways. The most common, as you noted, is convention: i, j, k for loop variables, x and y for coordinates, e for exceptions, f and g for functions and so on.

Another is structure. Often, the broad structure of an expression is more important than its contents. Using shorter variable names makes it easier to read at a glance. I think this is often more important than being easy to read in detail!

If a variable has a very small scope—say one or two lines at most—and it's easy to see where it comes from, having a long name is just noise.

https://www.quora.com/When-are-single-character-variable-names-acceptable/answer/Tikhon-Jelvis

Read more

Beyond Console Debugging Tricks

Daniel Reis shows some alternatives for the best known form of debugging JavaScript console.log.

I don’t consider myself a nitpicker. That’s only true, and it’s all fine and dandy… until I find a console.log() that someone forgot to remove from the JavaScript code. And if we’re talking about debugger statements… all hell breaks loose! ... I collected some of the most common examples I can present as proper alternatives for that process.

https://medium.com/outsystems-experts/beyond-console-debugging-tricks-f7d0d7f5df4

Read more

Using class_alias to maintain BC while moving/renaming classes

I've been using PHP for quite some time now, and I had never heard of class_alias before reading this post by Fabian Schmengler.

Sometimes you want to rename a class or move it to a different namespace. But as soon as it is used anywhere outside the package, this is breaking backwards compatibility and should not be done lightheartedly.

Luckily there is a way in PHP to have both, the old class and the new class, while deprecating the old one: class_alias().

https://www.schmengler-se.de/en/2016/09/php-using-class_alias-to-maintain-bc-while-move-rename-classes/

Read more

Preventing API drift with contract tests

In an older post on his blog Adam Wathan shared an interesting approach on how to prevent API drift between a test mock and an actual implementation.

One of the risks of writing your own test doubles is that the API of the double can fall out of sync with the API of the real implementation.

In this screencast I walk through an example that explains:

  • How interfaces can provide a false sense of security
  • Why tests make better contracts than interfaces
  • How to run multiple implementations against a shared set of contract tests

If you’ve ever had issues with API drift, try this approach and let me know how it works for you.

https://adamwathan.me/2016/02/01/preventing-api-drift-with-contract-tests/

Read more

Simplifying presenters in Laravel original

by Freek Van der Herten – 3 minute read

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. In case you've never…

Read more

Is your JavaScript function actually pure

What does “pure function” mean in the context of JavaScript? In programming in general, purity is also known as “referential transparency”, a fancy way of saying “replacing an expression or function call with its result will never change the behavior of the program” or a way of saying “every time you pass the same inputs, you always get the same outputs”.

That sounds intuitive, and a function like x => x * 10 looks pure because every single time you pass it the number 3 as argument you will get 30 as output. So how can we tell that one function is pure and the other isn’t? Is it enough that we just read the code?

Spoiler: reading the code isn't enough.

http://staltz.com/is-your-javascript-function-actually-pure.html

Read more

Hacking a PHP site

In the beginning of the summer the Belgian company PHPro held a cool hacking contest. The persons the could hack a special site that they had set up could win a prize. Yesterday they published an interesting article on how that site could be hacked. The site was also hacked in ways that the developers of the company did not anticipate.

Since this contest started out as an internal project, we've put a lot of focus on the flow on how to hack the website. It was just a little side project to inform our colleagues that some small mistakes can end up in a big catastrophe. By focussing on the flow of the hackme contest, we forgot to secure the application for malicious contestants. Off course, this was something that fired back to us on the first days of the competition. Here is a little write-up of the problems we've encountered and how we fixed them.

http://phpro.be/news/hackme-results

Read more

Hunting for great names in programming

A great story by DHH on his quest to find good names for some functions he was working on.

One of the real delights of programming is picking great variable, method, and class names. But an even greater treat is when you can name pairs, or even whole narratives, that fit just right. And the very best of those is when you’re forced to trade off multiple forces pulling in different directions.

https://m.signalvnoise.com/hunting-for-great-names-in-programming-16f624c8fc03

Read more

Laravel LTS is a Trap

A couple of months ago Jason McCreary, creator of Laravel Shift, wrote down his opinion on the Laravel's LTS release. I couldn't agree more with this piece.

The more developers that get trapped by LTS, the more of a drag it creates on the Laravel community. Potentially having adverse affects on its growth. Using LTS as a minimum compatibility line for a Laravel package or other third-party code is understandable. But freezing your apps to an LTS version is not. Your apps should run the latest stable version of Laravel.

https://medium.com/@jasonmccreary/laravel-lts-is-a-trap-97b1d1103961

Read more

Practicing YAGNI

In a new post on his blog Jason McCreary, creator of Laravel Shift, wrote down the summary of his Laracon US talk.

I consider myself a searcher. On a quest to find the Holy Grail of programming practices - that single practice which instantly levels up my skills. While I know this doesn’t exist, I do believe in a set of practices. Recently, I found one to be YAGNI.

YAGNI is a principle of eXtreme Programming - something I practice daily at work. YAGNI is an acronym for You Aren’t Gonna Need It. It states a programmer should not add functionality until deemed necessary. In theory, this seems straightforward, but few programmers practice it.

http://jason.pureconcepts.net/2016/08/practicing-yagni/

Read more

The traits of a proficient programmer

Gregory Brown wrote an excellent article on how you can grow as a programmer.

Do you know what the difference between competence and proficiency is? ... Competence means having enough experience and knowledge to get stuff done; proficiency involves knowing why you are doing something in a certain way, and how it fits into the big picture. In other words, a proficient practitioner is always a competent practitioner, but the opposite may not be true.

https://www.oreilly.com/ideas/the-traits-of-a-proficient-programmer

Read more

Testing your composer dependencies with prefer-lowest

An older but still relevant post by Evert Pot on why and how you should also test your packages with the lowest versions of it's dependencies.

In some projects, there may be packages lying around that are not the latest version. This could be because it introduced some BC break, or introduced a bug.

If other packages also use the package that’s being held back, they may get an older version as a dependency.

So for package maintainers, they will want to find out if their package correctly works with the oldest package they claim to support.

https://evertpot.com/testing-composer-prefer-lowest/

EDIT: Here's another old, but also still relevant, blogpost on the subject by Cees-Jan Kiewiet:

https://blog.wyrihaximus.net/2015/06/test-lowest-current-and-highest-possible-on-travis/

Read more

On Technical Debt: Shoveling forward

Fred Hébert on his blog:

... sooner or later, people start misinterpreting the original intent and thinking of technical debt the same way you could think about financial debt: a lever to use in order to get something now and then pay the accrued cost progressively over time. This is however not how things feel from the technical person's point of view. ... Rather than focusing on why that is wrong, I want to propose an alternative analogy to describe the reality behind technical debt.

http://ferd.ca/on-technical-debt-shoveling-forward.html

Read more