【问题标题】:Laravel save class namespace in a variable or constantLaravel 将类命名空间保存在变量或常量中
【发布时间】:2016-04-21 07:40:08
【问题描述】:

我已经这样实现了我的控制器:

class PayamAPIController extends Controller
{

    const THESIS = \App\Models\Thesis;


   public function getOffers($offerable)
     {
        // does not work
        $entities =  self::THESIS::where('user_id',\Auth::id())->get();
     }
}

这是我的控制器类的 simplifield 版本。

问题是我无法通过常量访问Thesis 模型。

PayamAPIController.php 第 27 行中的 FatalErrorException:语法错误,意外 '::' (T_PAAMAYIM_NEKUDOTAYIM)

我需要将我的模型存储在常量或变量中,并在控制器方法中使用它们

【问题讨论】:

  • 随便THESIS::where()->get()
  • 我需要引用常量并从那里获取模型

标签: php laravel constants


【解决方案1】:

无需创建常量,只需在'use'语句中包含对外部类的引用即可:

use \App\Models\Thesis;

class PayamAPIController extends Controller{
    $entities = Thesis::where('user_id',\Auth::id())->get();
}

【讨论】:

  • 谢谢,但这是我的控制器类的简化版本,我需要使用常量,如果你能找到一种通过常量访问模型的方法,我将不胜感激
  • @alex 你能解释一下为什么需要使用常量吗? use 语句会以正确的方式做同样的事情。
【解决方案2】:

如果你必须使用常量,试试这样的方法

protected static $model ='App\Models\MyModel';
//in function
$model = (new static::$model)->where('id', $this->id)->firstOrFail();

或者像克劳迪奥·金提到的那样包括use Model

【讨论】:

  • 我通常将它们声明为静态的,并且可以正常工作。更新答案
  • 谢谢,您的解决方案有效,但您使用的属性不是常量,是否可以使用常量来完成这项工作?
【解决方案3】:

找到了解决办法。只需在变量中声明对常量的引用,然后调用它:

 $model =  self::THESIS;
 entities = $model::where('whatever')->get();

【讨论】:

    【解决方案4】:

    你需要在一个变量中声明对constant的引用,然后调用它:

    class SomeController extends Controller 
    {
        protected const MODEL = SomeClass::class;
    
        public function doSomeThing()
        {
            $entities = (self::MODEL)::where('user_id',\Auth::id())->get();  
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 2014-07-05
      相关资源
      最近更新 更多