A
A
Alexey Konovalov2018-04-21 22:28:12
PHP
Alexey Konovalov, 2018-04-21 22:28:12

How to access a class from other classes?

Hello! Help me understand if I am doing authentication and requests for data related to it correctly ...
I am writing on the API site for the application and now the question arose with authentication (do not mess with authorization).
All requests to the API are made through one file (say index.php )
In this file, an object of the Auth (Singleton) class is created that checks the token and receives data (ID, Group, Permissions for this group, etc.) about the current user from the database .
Next, the called API method is checked and the required file (class) is connected via require_once .
And here is the problem. For example, I need to check if the user can write comments or posts, etc.
And for this I need to make a check in the $Auth->checkRole('add_comments ' ) method from the AddComment
class property through the method Well, then it's clear, in any method of the AddComment class, I simply refer to the Auth class through the $this->auth property as an object of the class. Is this the right approach? After all, I need to access the Auth class in almost every API class , and therefore add this line to every constructor$this->auth = $Auth::getInstance()

$this->auth = $Auth::getInstance()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maksim Fedorov, 2018-04-21
@Maksclub

In this file, an object of the Auth (Singleton) class is created that checks the token and receives data (ID, Group, Permissions for this group, etc.) about the current user from the database

What is this action for? Are you checking user rights here?
Maybe it's worth taking a ready-made solution? For example Zend ACL
https://framework.zend.com/manual/1.12/ru/zend.acl...

B
Boris Korobkov, 2018-04-21
@BorisKorobkov

Is this the right approach? After all, I need to access the Auth class in almost every API class, and therefore add this line $this->auth = $Auth::getInstance() to every constructor

If you want to push yourself and do everything according to SOLID, then yes, that's right.
If you want to do it simply and reliably, then you can type:
Yii::$app->user->can('add_comments')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question