By following the OOP approach, I am writing reusable methods into traits rather than creating a plain helper file. So that I can control access in an organized way. For that, I have created various traits for instance, permissions, auth, settings, helpers etc.
After working with PHP for more than seven years, I still feel there is a lot to learn.
Most traits have private and static methods. However, the helpers trait has all public methods. To call any method from the helpers trait to other trait's static method, I have to call it using (new self)->helper_method()
Question:
I would like to know if there is any drawback of using it often? If yes, is there any better way then it to access public method within the static method?
Example Code
This is an example of what I am trying to do.
permissions Trait
trait permissions {
private static function authorize() {
$role = ( new self() )->checkUserRole();
if ( $role == 'ultimate' ) {
return TRUE;
}
return FALSE;
}
}
auth Trait
trait auth {
public function checkUserRole( $userId = FALSE ) {
$user = $userId ? getUser( $userId ) : getCurrentUser();
if ( $user ) {
return $user->role;
}
return FALSE;
}
}
UltimatePost Class
class UltimatePost {
use permissions, auth, ...;
public function __construct() {
if ( ! self::authorize() ) {
return FALSE;
}
}
}
UltimateMedia Class
class UltimateMedia {
use permissions, auth, ...;
public function __construct() {
if ( ! self::authorize() ) {
return FALSE;
}
}
}
The drawback is that a class' constructor usually often probably should have <more softening adverbs here> required arguments. If your constructor doesn't take arguments, and instances are apparently entirely interchangeable, then it's questionable why you're using classes instead of a collection of functions in the first place.
If and when your classes require constructor arguments, you cannot willy nilly instantiate them, since you'll need to pass the required arguments, which your static method probably won't have.
In your case your classes just end up as a bunch of static function calls ending up with
getCurrentUser, so you don't seem to be using OOP much at all.You may be interested in How Not To Kill Your Testability Using Statics for a deeper dive into this topic.