【问题标题】:Using helper methods from Blade returning 'Cannot redeclare Class' error使用 Blade 中的辅助方法返回“无法重新声明类”错误
【发布时间】:2017-04-27 22:27:38
【问题描述】:

我试图从我的刀片视图中调用App\Http\Timeslot::isOpen(),但我不明白如何在不将 isOpen() 声明为静态的情况下调用它。我不能将其声明为静态,因为我需要使用构造中的 $this->hours。如果我不声明它,静态 laravel 将返回 Cannot redclare Class error

有人可以建议我应该如何编写这个以便我仍然可以访问 $this->hours 变量吗?

刀片模板:

@if(App\Http\Timeslot::isOpen())
    We're open
@else
    We're closed
@endif

时隙类

<?php namespace App\Http;

use App\OpeningHour;
use Carbon\Carbon;

class Timeslot
{
    protected $hours;

    public function __construct()
    {
        $this->hours = OpeningHour::all();
    }

    public static function isOpen()
    {
        // get current date
        Carbon::now()->format('w');
        $open_window =  $this->hours->get(Carbon::now()->format('w'));

        // is it over current days' opening hours?
        if(Carbon::now()->toTimeString() > $open_window->opening_time)
            return true;
        else
            return false;
    }
}

【问题讨论】:

    标签: php laravel oop ioc-container


    【解决方案1】:

    您也可以将 $hours 声明为静态,并在 isOpen() 中调用一个方法来检索/缓存它们。

    类似:

    <?php namespace App\Http;
    
    use App\OpeningHour;
    use Carbon\Carbon;
    
    class Timeslot
    {
         static protected $hours = null;
    
         public static function getOpeningHours()
         {
             if (self::$hours == null) {
                self::$hours = OpeningHour::all();
             }
         }
    
         public static function isOpen()
         {
             self::getOpeningHours();
    
            // get current date
            Carbon::now()->format('w');
            $open_window = self::$hours->get(Carbon::now()->format('w'));
    
            // is it over current days' opening hours?
            if (Carbon::now()->toTimeString() > $open_window->opening_time)
                return true;
            else
                return false;
         }
     }
    

    像这样,你不必使用构造函数。

    另一种方法(可能是更“Laravelish”的方法)是将您的课程迁移到服务提供者: https://laravel.com/docs/5.3/providers

    寻找“视图作曲家”,它们是将数据注入视图的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      相关资源
      最近更新 更多