I am a new PHP developer (coming from .NET). The experienced php dev that I work with said that calling a static get method on a PHP class with an ID as a parameter is common in PHP.
Is there a name for this idiom? Is there a reason why developers do this? Can someone point to a link to an example class?
I would like to understand more of what he is saying. He is talking about code like this I think, to pull car #1 from the database:
$car = Car::get(1)
3
This is the facade pattern and the purpose is to provide easy access to common or otherwise complicated tasks. Generally it just provides syntatic sugar. To compare it to the C# world think of it like extension methods:
Example of calculating the total transaction amount for a user traditionally:
var total = 0f;
foreach(var transaction in User.transactions) {
total += transaction.Amount;
}
Using an extension method:
// Extension Method
public static float AccountBalance(this User user) {
var total = 0f;
foreach(var transaction in User.transactions) {
total += transaction.Amount;
}
return total;
}
// Using the extension method
user.AccountBalance();
Likewise the same sort of thing happens using the facade pattern in PHP:
$total = 0;
foreach($user->trasnactions as $transaction) {
$total += $transaction->amount;
}
With a facade
<?php
class User {
public static function TotalTransactionSum($userid) {
$user = $userRepository->getById($userid);
$total = 0;
foreach($user->transaction as $transaction) {
$total += $transaction->amount;
}
return $total;
}
}
// Using the facade later
$total = User::TotalTransactionSum(1);
0
It’s called the Singleton pattern and it’s generally a bad design practice.
I’m assuming when you call Car::get(1)
on the data model for Car
it uses a singleton reference for the data source, queries the database and returns the record.
This is bad design.
Singletons hide the dependencies of the data model in the source code. The get()
method is made static to avoid passing around an object reference. This creates fractures in the connection between business logic and data models.
It’s just a really bad thing to do if this is how you’re accessing your data.
- It violates the Single Responsibility Principle because your models handle their own creation.
- It creates tightly coupled code that is difficult to maintain.
- It makes it very difficult to unit test.
- The data models state is changed by multiple points in the source code outside the scope of the current caller.
- The data models carry state changes into other business rules.
I could go on and on…
4