Static functions are bad, but what is the alternative?

In my example, I use the Yii2 PHP framework, but I think this applies to most OO languages.

I have a base class ActiveRecordthat most of my business objects extend from, for example. Project.

At the moment, if I want an instance Project, I call

Project::findOne(['id' => $id]);

findOne is a static method ActiveRecord(which is part of the Yii2 structure). So this is a bad form, because I cannot easily make fun of / muffle the return of this call when writing unit tests.

But what is the best way to get around this?

I could create a class CActiveRecordthat inherits from ActiveRecordand transfers the static call to a non-static call and uses it everywhere, but then I would have to instantiate the throw-away object Projectto streamline to get the actual instance. What if the object Projectneeded to create some heavy configuration to create an instance - I would pass random nonsense to the constructor to get the instance.

Summary: Just changing statics to non-statistics seems wrong - shouldn't I also move functions elsewhere? If yes, where?

+4
source share
1 answer

- . "" :

$c = new CProject;
$c->findOne(); // Calls Project::findOne()

. -> vs. ::, , - . , /, , .

:

function foo(Project $project) {
    $p = $project->findOne();
}

Project, , , Project. , Project interface. , - , , ; .

-, . , , , -, , , . / .

. Statics .

+7

Source: https://habr.com/ru/post/1613612/


All Articles