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;
}
}
}