PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 12, 2022

[FIXED] How to get current controller action in cakephp 3.x model

 January 12, 2022     cakephp, cakephp-3.0, cakephp-3.x     No comments   

Issue

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


Solution

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



Answered By - Rohit Ailani
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing