Poor man's caching
Although there are many solutions out there when it comes to caching, I have found a few occassions where it was actually as straight-forward as a single line of code.
When I first learned about the "null coalescing assignment operator" in PHP (yeah, it's quite a mouthful), I almost immediately embraced it by replacing this:
if(!isset($this->var)) {
$this->var = 'value';
}
return $this->var;
...to this: 😏
return $this->var ??= 'value';
At the same time this can be a useful way of ensuring that variables, or properties, are only set if they haven't been set in the first place. This results in a very compact way of conditionally caching data, for instance.
I now what you might be thinking. What's so wrong about re-setting a textual variable? Well, nothing. It becomes worth considering once you're dealing with a database query, for instance.
Imagine the following code:
public static function getData(): \App\Models\Post
{
return Post::get()->first();
}
public static function getName(): string
{
return $this->getData()->name;
}
public static function getEmail(): string
{
return $this->getData()->email;
}
You see where I'm getting at. Multiple queries. If we had defined this variable only once from the start, this wouldn't result in multiple queries, but instead simple returned the locally available data property.
I realize there are tons of ways to do this, like using the constructor. However, there are times when I personally feel like defining and returning properties on the fly, sort to speak, while not having to do so at a cost. That's where this small, but effective method comes in.
public static function getData(): \App\Models\Post
{
return $this->data ??= Post::get()->first();
}
// etc.
Doing so, no matter how many times this method is used throughout our code, the database will only be queried once, which is rather reassuring in many cases.
Warning: I believe PHP 8.3 will prevent you from dynamically defining properties. So always be sure to define the property (data
, in our case) in your class before assigning values.
Conclusion
This small native PHP trick can be used to simplify some of your code and optimize your queries in the process. I found it to be quite convenient. There are people who claim that readability may be in favor of the traditional way, I am personally more of a progressive type of person. If you ask me, you can always add a comment in case you're hesitant about implementing the newer method.