Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在静态方法中使用会话(cakephp 4和3.6+;)_Php_Cakephp_Cakephp 3.0 - Fatal编程技术网

在静态方法中使用会话(cakephp 4和3.6+;)

在静态方法中使用会话(cakephp 4和3.6+;),php,cakephp,cakephp-3.0,Php,Cakephp,Cakephp 3.0,如果我尝试,这是一个具有静态方法的类: public static function chkLog($role) { $userrole = $this->getRequest()->getSession()->read('userrole'); return $userrole; /// more code 甚至尝试过: public static function chkLog($role) { $userrole = Session:

如果我尝试,这是一个具有静态方法的类:

public static function chkLog($role)
{
    $userrole = $this->getRequest()->getSession()->read('userrole');
   return $userrole;
   /// more code
甚至尝试过:

    public static function chkLog($role)
{
    $userrole = Session::read('userrole');
   return $userrole;
   /// more code
在拉雷维尔,我可以:

public static function userRole($role = null)
{
    $userrole = Auth::user()->role;
    $checkrole = explode(',', $userrole);
    if (in_array($role, $checkrole)) {
        return $role;
    }
    return false;
}
用法

但在cakephp中,为了静态调用,我必须编写以下代码:

    public static function __callStatic($method, $params)
{
    $instance = ChkAuth::class;
    $c = new $instance;
    return $c->$method(...array_values($params));
}
为了称之为:

public function userRole($role = null)
{
    $userrole = $this->getRequest()->getSession()->read('userrole');
    $checkrole = explode(',', $userrole);
    if (in_array($role, $checkrole)) {
        return $role;
    }
    return false;
    // more
使用方法:

   public function getPets($offset = "", $rowsperpage = "", $petsearch = "")
{
    $pagingQuery = "LIMIT {$offset}, {$rowsperpage}";
    $petsearch = $petsearch . "%";
    if (Auth::chkRole('admin') === true) {
        return DB::select("SELECT * FROM " . PREFIX . "pets " . $pagingQuery);
    }
    $authid = Auth::authId();
    return DB::select("SELECT * FROM " . PREFIX . "pets WHERE ownerid = :authid " . $pagingQuery, ["authid" => $authid]);
}
所以,基本上,我想弄清楚如何在静态方法中使用cake php中的会话


注意uu callStatic可以工作,但作为一个循环的工作。

CakePHP的
Router
类包含一个静态函数来返回请求对象。请求对象包括一个返回会话的函数。因此:

Router::getRequest()->session()
或者,从3.5版开始:

Router::getRequest()->getSession()

感谢getSession的成功。奇怪的是,4.0手册中关于会话的章节中没有提到这一点null@tfont,您正在运行什么版本的CakePHP?
Router::getRequest()->getSession()