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

Don't call instance methods statically
Jul 25, 2017 @ 11:16:39

In this new post on thePHP.cc site they talk about calling instance methods statically, more specifically that it should be avoided.

There are quite a few things in PHP 4 that were a bit strange. One example is that PHP 4 allowed static calling of instance methods. [...] To keep backwards compatibility with PHP 4, this code works up to PHP 5, even though [the method in the example[ is not declared static.

[...] Now things will get really weird. When calling an instance method of another class statically, the $this context would carry over from the caller to the called class. In other words, $this suddenly refers to another object instance. While in PHP 5, this used to be an E_STRICT error, PHP 7 will emit an E_DEPRECATED error.

They point out that, while this is definitely odd behavior that shouldn't exist, it hasn't been removed because of PHP's backwards compatibility principles and only removing functionality like this in major versions. So, instead, they recommend calling all non-static methods using an instance of the class injected rather than directly calling them.

tagged: instance method call static object avoid error

Link: https://thephp.cc/news/2017/07/dont-call-instance-methods-statically

DaedTech Blog:
Avoid these Things When Logging from Your Application
Dec 06, 2016 @ 11:53:48

On the DaedTech blog Erik Dietrich has written up a list of a few things he suggests avoiding when using logging functionality in your application. The suggestions range from the actual contents of the message out to some logging best practices.

It seems almost strange to talk about avoiding things while logging. After all, logging is your last line of defense or your salvation in many cases. [...] Well, it turns out that, while logging may be a highly inclusive activity in terms of what should be included, there are ways to create problems. You want to be liberal in terms of what you log, but judicious and wise in terms of how you log it. You don’t want to indulge in a feckless free-for-all when it comes to the calls you make to your application’s logger.

So what are these problems, and how to avoid them? Let’s take a look at some things that can come back to bite you.

He points out the following (common) bad practices he has seen during his time developing:

  • Forgetting Context
  • Cryptic Codes
  • Spamming the Log File
  • Unsafe Logging Calls
  • Mixing Application Logic with Logging

He ends the post with a suggestion of "sensible logging" - capturing as much meaningful information as possible while not overdoing it. Logs can be a powerful ally when hunting down an issue or trying to provide documentation of a security issue. Log wisely, log on purpose.

tagged: logging practices recommendation avoid list

Link: http://www.daedtech.com/avoid-things-logging-application/

Phil Sturgeon:
Avoid Hardcoding HTTP Status Codes
Aug 17, 2015 @ 12:55:53

Phil Sturgeon has a post to his site with a good recommendation for those working with APIs and those "magic numbers" that are HTTP status codes - avoid hard coding them in your applications and tests.

A lot of things in programming are argued to death, but one subject where people almost unanimously agree is that magic numbers can be a pain in the ass, and they should be avoided whenever possible. Sadly when it comes to HTTP status codes, people keep on hardcoding them, and it leads to all sorts of confusion. [...] What is 409? If you answer without looking it up on Dash or HTTP Status Dogs then you are a machine.

He shows two implementations of this idea, one in Ruby and the other in Symfony, where the status code value is represented by a constant rather than by a number. The constant correlates to the HTTP status code (number) but the constant makes it easier to read and understand the code. He points out two libraries that can be substituted into your current testing to replace those hard coded values with more expressive versions: lukasoppermann/http-status and Teapot.

tagged: avoid hardcode http status code opinion expressive teapot httpstatus

Link: https://philsturgeon.uk/http/2015/08/16/avoid-hardcoding-http-status-codes/

Why Doctrine ORM is not suited for PHP
May 20, 2015 @ 12:09:42

The ByMyCTO.com blog has a recent post that makes the suggestion that the Doctrine ORM isn't suited for PHP...or to put it another way why they think it's not a good option for database integration.

I know, this title sounds like a troll. But it’s not, it’s a fact. I’m not saying Doctrine is a bad technology or shouldn’t be used. I’m just saying it’s not suited for PHP and this can lead to critical problems if misused.

He covers a few different topics including:

  • Differences between Java and PHP (and the fact that Doctrine's inspiration was Hibernate)
  • The "session problem" (entity serialization)
  • Identity Map, useless in a stateless environment
  • UnitOfWork, far too complex
  • EntityManager, too magical

Despite all of these points, he does remind the reader that Doctrine isn't useless or inherently bad, it's just that he sees it as reinforcing bad behaviors and suggests using something else.

tagged: doctrine orm avoid critical problem opinion

Link: http://blog.bemycto.com/software-architecture/2015-05-17/doctrine-orm-not-suited-php/

Sahand Saba:
9 Anti-Patterns Every Programmer Should Be Aware Of
May 13, 2015 @ 11:29:50

In a recent post to his site Sahand Saba has posted a list of nine anti-patterns every programmer should avoid. This list isn't language specific and ranges in types of advice from general programming practices down to more specific "code smells" to avoid. The code examples are in Python but you can interpolate them into the world of PHP pretty easily.

A healthy dose of self-criticism is fundamental to professional and personal growth. When it comes to programming, this sense of self-criticism requires the ability to detect unproductive or counter-productive patterns in designs, code, processes, and behaviour. This is why a knowledge of anti-patterns is very useful for any programmer. This article is a discussion of anti-patterns that I have found to be recurring, ordered roughly based on how often I have come across them, and how long it took to undo the damage they caused.

The list of nine includes things like:

  • Premature Optimization
  • God Class
  • Inner-platform Effect
  • Management by Numbers

Each item on the list includes a few subheadings talking about what it is, why it's bad, how to avoid it and some code examples (where appropriate) to find it in your code.

tagged: antipatterns nine list programmer avoid opinion

Link: http://sahandsaba.com/nine-anti-patterns-every-programmer-should-be-aware-of-with-examples.html

Pádraic Brady:
TLS/SSL Security In PHP: Avoiding The Lowest Common Insecure Denominator Trap
Apr 24, 2015 @ 10:30:50

In his latest post Pádraic Brady shares his thoughts about the state of TLS/SSL functionality in PHP and how he thinks developers should avoid the trap of "lowest common denominator" and opt for insecurity.

A few weeks back I wrote a piece about updating PHARs in-situ, what we’ve taken to calling “self-updating”. In that article, I touched on making Transport Layer Security (TLS, formerly SSL) enforcement one of the central objectives of a self-updating process. In several other discussions, I started using the phrase “Lowest Common Insecure Denominator” as a label for when a process, which should be subject to TLS verification, has that verification omitted or disabled to serve a category of user with poorly configured PHP installations.

This is not a novel or even TLS-only concept. All that the phrase means is that, to maximise users and minimise friction, programmers will be forever motivated to do away with security features that a significant minority cannot support by default.

He goes on to talk about how, in some places, targeting the lowest common denominator is okay, security isn't one of them. He also includes four basic concepts developers can adhere to to prevent this targeting:

  • You should never knowingly distribute insecure code.
  • You should accept responsibility for reported vulnerabilities.
  • You should make every effort to fix vulnerabilities within a reasonable time.
  • You should responsibly disclose vulnerabilities and fixes to the public.

He follows these up with three steps you can follow to migrate an insecure architecture into something much more robust. This includes identifying the consequences of the update and documenting the solutions you've chosen, be those configuration updates or library changes.

tagged: tls ssl security lowest common insecure denominator trap avoid

Link: http://blog.astrumfutura.com/2015/04/tlsssl-security-in-php-avoiding-the-lowest-common-insecure-denominator-trap/

Piotr Pasich:
ClassManager - You shall not pass
Jan 30, 2015 @ 11:42:55

Piotr Pasich has shared some thoughts on naming in his latest post to his site today. In it he talks about one of the "hardest things in computer science" (naming things) and makes some recommendations to help you make naming in your code more effective.

Precise names for classes is notoriously difficult. Done right, it makes code more self-documenting and provides a vocabulary for reasoning about code at a higher level of abstraction. There are a couple simple tips&tricks to make the names more readable: do not abbreviate, do not add any extra informations (underscore, type), avoid single letter prefixes, etc etc.

But what if you already know and use those rules and you still want to improve naming in your code? I assume that you care, you’re not selfish and you think about elses when you write the code. You ask one of the most important question to yourself, during architecture implementation – how the fellow sitting next to will behave while reading the code.

He's broken up the remainder of the post into different sections, each with a high level recommendation and some follow up description:

  • Ask somebody else
  • Does it have a single responsibility you can name?
  • Simple Superclass Name
  • Qualified Subclass Name
  • Adding ‘Interface’ word

He ends with a few names to avoid (like *Manager, *Helper or *Handler) to help prevent ambiguity. He reinforces providing meaning in your naming and making it easier for others to understand what's going on.

tagged: classmanager naming opinion recommendation avoid meaning

Link: http://piotrpasich.com/classmanager-you-shall-not-pass/

Benjamin Eberlei:
Traits are Static Access
Apr 12, 2013 @ 11:16:35

In a new post to his site Benjamin Eberlei shares an opinion about traits, noting that they're basically the same as static functionality when it comes to several things like coupling, not being testable and being a "global state" container.

I used to look forward to traits as a feature in PHP 5.4, but after discussions with Kore I came to the conclusion that traits are nothing else than static access in disguise. They actually lead to the exact same code smells. Familiar with the outcome of too much static use, we should reject traits as just another way of statically coupling your code to other classes.

He includes some code examples showing traits in use in an example controller to handle a simple redirect. He points out at least six different issues with just this simple implementation. He rewrites it as "static" code to help prove his point. He comes to the conclusion that, much like static methods, traits should be avoided and instead aggregation should be favored.

tagged: traits static compare avoid example code

Link: http://www.whitewashing.de/2013/04/12/traits_are_static_access.html

Avoid the Original MySQL Extension, Part 2
Feb 25, 2013 @ 13:40:09

PHPMaster.com has posted the second part of their "avoid the original MySQL extension" tutorial series (part one is here). In this new part, they share more about another alternative - the PDO extension.

The PDO extension supports twelve drivers, enabling it to connect to a variety of relational databases without the developer having to learn a number of different APIs. It does this by abstracting the database interaction calls behind a common interface, enabling the developer to utilize a consistent interface for different databases. This of course gives it a major advantage over both the MySQL and MySQLi extensions who are limited to only one database.

Included in the post are examples of some of the basics - connecting, executing queries, getting the results - as well as more compelx things like binding parameters and transaction support. There's also a bit about changing the default behavior of the PDO object through config options. He finishes off the article talking some about some of the issues that could come from using an abstraction layer like this and the need to still write good, compatible SQL depending on the database.

tagged: mysql extension avoid pdo tutorial abstraction


Michael Nitschinger:
A Journey on Avoiding Nulls in PHP
Feb 20, 2013 @ 12:17:39

Michael Nitschinger has written up a post looking at avoiding nulls in your applications in favor of a better kind of value handling - the introduction of "Optional" handling.

While every developer has kind of accepted their existence, they are suddenly there when we'd desperately need them to not show up. How often did you writeif($obj === null) in your PHP code? Can't there be a better, more elegant and fault-tolerant solution to the problem?

His solution is to create a PHP version of this "Optional" functionality (via an abstract class) that allows some evaluation of the returned value from method calls on the object. Methods like "isPresent", "getOrElse", "of" and "fromNullable" make it easier to work with null values instead of just the triple-equals checking. He includes not only the code for the classes you'll need to implement it but examples of it in use - an "Optional" abstract class and two child classes, "Present" and "Absent".

tagged: avoid null return value optional absent present evaluation tutorial