如何在Laravel 5项目中组织课程? [英] How can I organise classes in a Laravel 5 Project?

查看:78
本文介绍了如何在Laravel 5项目中组织课程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用任务管理应用程序.在App中,有一个 User 模型,有一个 Project Task 模型.

I am working on a Task Management App. In App there is a User Model and there is Project and Task models.

为了让用户添加项目和相关任务,我在模型级别要做的只是:

In order for user to add a Project and related Task, all I would do at Model Level is:

class Project extends Model
{
    public function add($user_id,$task_details)
    {
        //Add Project Meta
        $this->title = "Project Title";
        $this->description "Desc"
        $this->save()

        for($t=0;$t<count($task_details);$t++) {
        //Add Task Details
        $task = new Task();
        $task->title = $task_details["title"];
        $task->description = $task_details["description"];
        $task->save();
        }
    }
}

在我看来笨拙.我如何在Laravel 5中改善这一点?如何使我的模块更具原子性?

It looks clumsy to me. How can I improve this in Laravel 5? How can I make my modules more atomic?

推荐答案

是的,它很笨拙.您应该使用存储库模式,这样就不会存在此类多种职责. 而且Eloquent已经有了 findorCreate 之类的创建方法,或者只是创建方法. 这是UserRepository的简单示例.

Yeah it is clumsy. You should use Repository pattern so that there is no such type of multiple responsibilities. And Eloquent already has a create method like findorCreate or just create method. Here is simple example for UserRepository.

//UserRepository
<?php namespace App\Repository\User;
use App\User;


class UserRepository{
   public $model;
   public function __construct(User $userModel) // type hinting the User Model
   {
     $this->model=$userModel;
   }
   public function create($inputs)
   { 
      return $this->model->create($inputs);
   }

}


// UserController

<?php namespace App\Http\Controllers;
use \App\Repository\User\UserRepository;
class UserController extends Controller{

   public $userRepo;

   public function __construct(UserRepository $userRepository) //type hinting the userRepository Class
   {
      $this->userRepo=$userRepository;
   }

   public function getUser($id)
   {
      return $this->userRepo->model->findorfail($id);
   }
   public function getCreate()
   {
      if($this->userRepo->create(Input::all())
        return view('success');
      return Redirect->back()->withErrors();
   }
} 

这篇关于如何在Laravel 5项目中组织课程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆