The title is a bit misleading because I know it's not possible to share a static var over the children, but I'm searching for a way to fix my problem without doing it with a shared static var.
I have a superclass called 'Model' and some underlying child-classes called 'User' and 'Company'. I want to automate as much as possible, so that the subclasses only have fields and nothing more.
I want to create static 'GetAll' and 'GetByKey' methods in the superclass, so that I can use the following code:
$users = User::getAll();
$company = Company::getByKey(34); // Where 34 is the ID.
In my case, the Company class should know his primary key, without me telling him every time. I wan't to avoid methods like this in the child-classes:
public static function getByUserId($userId)
{
return static::find(array('userId' => $userId));
}
To do this, I created a static variable 'primaryKey' in the superclass. The problem is, there is no perfect place to 'set' the variable. The constructor won't be used if the only thing I do is getting all Users. Next to that, the static variable belongs to Model, which means that it will be overridden, if I have code like this:
$company = new Company(); // Model sets 'primaryKey' to 'id'
$user = User::GetByKey('myUsername'); // The 'primaryKey' is still 'id', but it should be 'username'
I do want to save the $primaryKey because getting the primary key from MySQL, every time I request some models, is just overhead.
Is there any way to give the subclasses their own static variable-values without creating them in the specific classes? I want to minimize the amount of work done for the Models. Using reflection or magic methods is no problem at all. In the most absurd-situation I have to make a DatabaseManager which has an array that holds all information from all models.
Note: I'm asking if there is a solution for my problem, even if it's not recommended or ugly code. I know that this question has been asked many times.
Thanks in advance,