【问题标题】:Laravel Artisan Command and Repository Datatype CheckingLaravel Artisan 命令和存储库数据类型检查
【发布时间】:2014-02-24 01:18:35
【问题描述】:

我正在寻求帮助,在我正在进行的一个小型 Laravel 4 项目中实施一些最佳实践。我在下面的 sn-ps 进行了简化,以帮助理解我想要理解的内容。


笔记库片段

...

public function deleteNotesOlderThan($days)
{
    if (!is_int($days)) {
        /* @TODO - Something here and return error possibly NULL? */
    }

    $date = new \Carbon\Carbon();
    $date = $date->subDays($days);
    Note::where('created_at', "<", $date)->delete();
}

...

我在 Controllers 和 Artisan 命令中注入了这个特定的存储库。我的问题与检查参数 $days 的数据类型并在正确的位置返回错误有关。如果 $days 不是 int,我应该返回什么类型的错误,可以在我注入的控制器和命令中使用?请参阅下面的命令。


注意工匠命令:

public function fire()
{
    $days = $this->option('days');

    if (!$days) {
        $days = 30;
    }

    if(!is_int($days)) {
        $this->error("Failure - The 'Days' option must be a valid integer");
        return false;
    }

    // $this->note is being injected into command via construct
    $this->note->deleteNotesOlderThan($days);

    $this->info('Success - Notes older than ' . $days . ' days(s) have been deleted.');
}

正如您在我的命令中看到的,我正在检查以确保 $days 再次是一个整数。我想我的问题是,这里的最佳做法是什么。如果我正在执行 $this->note->deleteNotesOlderThan($days) 并且该特定方法已经确保 $days 是一个 int,那么给出错误但干燥的最佳方法是什么?我希望这是有道理的。

提前致谢。

【问题讨论】:

    标签: php oop laravel repository


    【解决方案1】:

    在你的函数中,

        public function deleteNotesOlderThan($days)
        {
            if (!is_int($days)) {
                return FALSE;
            }
    
            $date = new \Carbon\Carbon();
            $date = $date->subDays($days);
            Note::where('created_at', "<", $date)->delete();
            return TRUE;
    
        }
    

    在工匠命令中,


            public function fire()
            {
                $days = $this->option('days');            
                if (!$days) {
                    $days = 30;
                }       
                if($this->note->deleteNotesOlderThan($days)){
                    $this->info('Success - Notes older than ' . $days . ' days(s) have been deleted.');
                }else{
                     $this->error("Failure - The 'Days' option must be a valid integer");
                }                   
            }
    

    这就是我会做的。

    【讨论】:

    • 谢谢!我最终选择了这样的东西。
    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2017-06-13
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多