2
votes

I am using cakephp 3.x have put database queries in model in which i want to check the current controller action and based on that i will make my database queries.

I know i can pass controller action from my controller itself to my model function but is there a way i can just check my current controller action inside my model only so that i do not need to pass it in my multiple functions which are inside model only.

My Try -- UsersTable.php

    public function initialize(array $config)
    {
        parent::initialize($config);
        $this->table('users');        
        $this->primaryKey('user_id');
        echo '<pre>';
        print_r($GLOBALS);        
        exit;
    }

so far if i do this, i got an array in response and in which i found this the best result out of other things in that array

[REQUEST_URI] => /5p_group/users/add

I m also trying to use this

echo '<pre>';
print_r($GLOBALS['_SERVER']['HTTP_REFERER']);        
exit;

which gives me this output

http://localhost/5p_group/users/archived

so eventually i am getting the result which i want but i want another proper method which cakephp 3.x uses ..

So is there any other way or more frequent way from that i can get my current controller action ?

Any ideas will be appreciated ..

Thanks

2
That's a clear violation of separation of concerns, ie a very bad idea, your model is not supposed to know about the outside world and make such decisions! If a controller wants data from a model, then it tells the model what data it wants, not the other way around! You may get better help if you elaborate on what exactly you need to query when exactly. - ndm
i know it does not make sense .. but is it wrong to know the stuff ? - Mittul At TechnoBrave
It's never wrong to know about stuff, no, like bad practices and how to avoid them. And if you want to know even more, like how to do it the right way, then please elaborate on the actual technical problem that you are trying to solve, ie als already mentioned, "what exactly do you need to query when exactly?". - ndm
I agree with you for this statement and it makes sense to me. Thanks - Mittul At TechnoBrave

2 Answers

5
votes

First of all you should use the routing class in your model. So at the top you can call it like below

use Cake\Routing\Router;

And then in your initialize function you can check the params like

debug(Router::getRequest());

Or to be more specific you can use

debug(Router::getRequest()->params['action']);

I think this is the solution using cakephp classes only, though a small hack.

For more function reference you can access the cookbook at Router Class

0
votes

The question was about a Model, but it shows up on Google.

When inside a view (.ctp file), use

\Cake\Routing\Router::getRequest()->getAttributes();

CakePHP 3