简体   繁体   中英

Yii and static functions

Is it bad practice to have a lot of static functions? I am using Yii framework and I realized I have a lot of static functions in my model classes. I put all my functions that have to do with Users into the UsersModel (I do the same for other models too) but I end up with a lot of static functions. Just wondering how you guys deal with this. A lot of these functions are just query builder functions instead of lazy loading because I need to increase database performance.

Example functions:

User::getUserFromCampaign(1)
User::getUsersNotInCamapaigns()
User::isAdmin()

Instead of using static functions, what you can do is instantiate an object of the User class (which would presumably not be a static class) in the models that require those methods, and use the object's methods directly.

This also means that those methods will only be loaded on objects that require them, instead of being "global".

Here is a good answer on this : https://softwareengineering.stackexchange.com/questions/98083/cant-i-just-use-all-static-methods

Instantiating your classes is best for testing but there is no problem using static for certain tasks.

A lot of it is down to opinion, if your code works, it's running efficiently and easy to maintain then all is dandy!

Also to add to the Laravel facade comments. Laravel does instantiate the class, a facade just provides a simplified interface to the bigger picture lets say.. that's exactly what laravel is doing. The end result is really nice readable code.

MVC is a nice design pattern and it has its place. The Factory design pattern is another nice pattern. In case you're unfamiliar with it, Google for Factory design pattern . In a few words: a FooFactory is a class that generates objects of the Foo class (or FooModel class, if you will).

MVC and Factory are not mutually exclusive, so you could refactor a lot of those static methods into a new UserFactoryClass.

  • User::getUserFromCampaign(1) to me, is a bit weird, though. I take it that 1 is a campaign ID? Then what user does it return? Or can a campaign only have one user? If that is the case, then UserFactory::getUserFromCampaign() will return a UserModel object for the user in the campaign with the given ID.

  • User::getUsersNotInCampaign() , I assume, returns an array of UserModel objects? Refactor it into `UserFactory::getUsersNotInCampaign() and there you go.

  • User::isAdmin() shouldn't be static at all. if ($user->isAdmin()) ... , not if(User::isAdmin($user))...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM