php MVC(Laravel)在哪里添加逻辑
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23595036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC (Laravel) where to add logic
提问by Sabrina Leggett
Let's say whenever I do a CRUD operation or modify a relationship in a specific way I also want to do something else. E.g., whenever someone publishes a post I also want to save something to a table for analytics. Maybe not the best example but in general there's a lot of this "grouped" functionality.
假设每当我执行 CRUD 操作或以特定方式修改关系时,我还想做其他事情。例如,每当有人发布帖子时,我也想将某些内容保存到表中以进行分析。也许不是最好的例子,但总的来说,有很多这种“分组”功能。
Normally I see this type of logic put into controllers. That's all fine an dandy until you want to reproduce this functionality in lots of places. When you start getting into partials, creating an API and generating dummy content it becomes an issue with keeping things DRY.
通常我会看到这种类型的逻辑放入控制器中。在您想在很多地方重现此功能之前,这一切都很好。当您开始进入部分、创建 API 并生成虚拟内容时,保持事物干燥就成为一个问题。
The ways I've seen to manage this are events, repositories, libraries, and adding to models. Here are my understandings of each:
我见过的管理方法是事件、存储库、库和添加到模型。以下是我对每一个的理解:
Services:This is where most people would probably put this code. My main issue with services is that sometimes it's hard to find specific functionality in them and I feel like they get forgotten about when people are focused on using Eloquent. How would I know I need to call a method publishPost()
in a library when I can just do $post->is_published = 1
?
服务:这是大多数人可能会放置此代码的地方。我对服务的主要问题是,有时很难在其中找到特定的功能,而且我觉得当人们专注于使用 Eloquent 时,它们会被遗忘。publishPost()
当我可以这样做时,我怎么知道我需要调用库中的方法$post->is_published = 1
?
The only condition I see this working well in is if you ONLY use services (and ideally make Eloquent inaccessible somehow from controllers all together).
我认为这种方法运行良好的唯一条件是,您是否只使用服务(理想情况下,控制器无法以某种方式访问 Eloquent)。
Ultimately it seems like this would just create a bunch of extra unnecessary files if your requests generally follow your model structure.
最终,如果您的请求通常遵循您的模型结构,这似乎只会创建一堆额外的不必要的文件。
Repositories:From what I understand this is basically like a service but there's an interface so you can switch between ORMs, which I don't need.
存储库:据我所知,这基本上就像一个服务,但有一个接口,因此您可以在我不需要的 ORM 之间切换。
Events:I see this as the most elegant system in a sense because you know your model events are always going to be called on Eloquent methods, so you can write your controllers like you normally would. I can see these getting messy though and if anyone has examples of large projects using events for critical coupling I'd like to see it.
事件:我认为这是某种意义上最优雅的系统,因为你知道你的模型事件总是会在 Eloquent 方法上被调用,所以你可以像往常一样编写控制器。我可以看到这些变得混乱,如果有人有使用事件进行关键耦合的大型项目的示例,我希望看到它。
Models:Traditionally I'd have classes that performed CRUD and also handled critical coupling. This actually made things easy because you knew all functionality around CRUD + whatever had to be done with it was there.
模型:传统上,我有执行 CRUD 并处理关键耦合的类。这实际上使事情变得简单,因为您知道 CRUD 的所有功能以及必须使用它完成的任何操作。
Simple, but in MVC architecture this isn't normally what I see done. In a sense though I prefer this over services since it's a bit easier to find, and there are less files to keep track of. It can get a bit disorganized though. I'd like to hear downfalls to this method and why most people don't seem to do it.
简单,但在 MVC 架构中,这通常不是我所看到的。从某种意义上说,我更喜欢这个而不是服务,因为它更容易找到,而且要跟踪的文件更少。不过,它可能会变得有点混乱。我想听听这种方法的缺点以及为什么大多数人似乎不这样做。
What are the advantages / disadvantages of each method? Am I missing something?
每种方法的优点/缺点是什么?我错过了什么吗?
回答by Luís Cruz
I think all patterns / architectures that you present are very useful as long as you follow the SOLIDprinciples.
我认为只要您遵循SOLID原则,您提出的所有模式/架构都非常有用。
For the where to add logicI think that it's important to refer to the Single Responsibility Principle. Also, my answer considers that you are working on a medium / large project. If it's a throw-something-on-a-pageproject, forget this answer and add it all to controllers or models.
对于在哪里添加逻辑,我认为参考单一职责原则很重要。另外,我的回答认为您正在从事中/大型项目。如果它是一个在页面上扔东西的项目,请忘记这个答案并将其全部添加到控制器或模型中。
The short answer is: Where it makes sense to you (with services).
简短的回答是:对您有意义的地方(提供服务)。
The long answer:
长答案:
Controllers: What is the responsibility of Controllers? Sure, you can put all your logic in a controller, but is that the controller's responsibility? I don't think so.
控制者:控制者的职责是什么?当然,您可以将所有逻辑放在控制器中,但这是控制器的责任吗?我不这么认为。
For me, the controller must receive a request and return data and this is not the place to put validations, call db methods, etc..
对我来说,控制器必须接收请求并返回数据,这不是放置验证、调用数据库方法等的地方。
Models: Is this a good place to add logic like sending an welcome email when a user registers or update the vote count of a post? What if you need to send the same email from another place in your code? Do you create a static method? What if that emails needs information from another model?
模型:这是添加逻辑的好地方,比如在用户注册或更新帖子的投票计数时发送欢迎电子邮件?如果您需要从代码中的另一个位置发送相同的电子邮件怎么办?您是否创建了静态方法?如果该电子邮件需要来自其他模型的信息怎么办?
I think the model should represent an entity. With Laravel, I only use the model class to add things like fillable
, guarded
, table
and the relations (this is because I use the Repository Pattern, otherwise the model would also have the save
, update
, find
, etc methods).
我认为模型应该代表一个实体。随着Laravel,我只用模型类添加之类的东西fillable
,guarded
,table
和关系(这是因为我使用Repository模式,否则模型本来也有save
,update
,find
,等方法)。
Repositories (Repository Pattern): At the beginning I was very confused by this. And, like you, I thought "well, I use MySQL and thats that.".
存储库(Repository Pattern):一开始我对此非常困惑。而且,和你一样,我想“好吧,我使用 MySQL,仅此而已。”。
However, I have balanced the pros vs cons of using the Repository Pattern and now I use it. I think that now, at this very moment, I will only need to use MySQL. But, if three years from now I need to change to something like MongoDB most of the work is done. All at the expense of one extra interface and a $app->bind(?interface?, ?repository?)
.
但是,我已经平衡了使用存储库模式的利弊,现在我使用它。我认为现在,此时此刻,我只需要使用 MySQL。但是,如果三年后我需要改用 MongoDB 之类的东西,那么大部分工作就完成了。所有这些都以一个额外的接口和一个$app->bind(?interface?, ?repository?)
.
Events (Observer Pattern):Events are useful for things that can be thrown at any class any given time. Think, for instance, of sending notifications to a user.
When you need, you fire the event to send a notification at any class of your application. Then, you can have a class like UserNotificationEvents
that handles all of your fired events for user notifications.
事件(观察者模式):事件对于可以在任何给定时间在任何类中抛出的事物很有用。例如,考虑向用户发送通知。当您需要时,您可以触发该事件以在您的应用程序的任何类中发送通知。然后,您可以拥有一个类似的类UserNotificationEvents
来处理所有触发用户通知的事件。
Services: Until now, you have the choice to add logic to controllers or models. For me, it makes all sense to add the logic within Services. Let's face it, Services is a fancy name for classes. And you can have as many classes as it makes sense to you within your aplication.
服务:到目前为止,您可以选择向控制器或模型添加逻辑。对我来说,在 Services 中添加逻辑很有意义。让我们面对现实吧,服务是类的一个奇特名称。并且您可以在您的应用程序中拥有尽可能多的类。
Take this example: A short while ago, I developed something like the Google Forms. I started with a CustomFormService
and ended up with CustomFormService
, CustomFormRender
, CustomFieldService
, CustomFieldRender
, CustomAnswerService
and CustomAnswerRender
. Why? Because it made sense to me. If you work with a team, you should put your logic where it makes sense to the team.
举个例子:不久前,我开发了类似谷歌表单的东西。我从 a 开始,CustomFormService
最后是CustomFormService
, CustomFormRender
, CustomFieldService
, CustomFieldRender
,CustomAnswerService
和CustomAnswerRender
。为什么?因为这对我来说很有意义。如果你和一个团队一起工作,你应该把你的逻辑放在对团队有意义的地方。
The advantage of using Services vs Controllers / Models is that you are not constrained by a single Controller or a single Model. You can create as many services as needed based on the design and needs of your application. Add to that the advantage of calling a Service within any class of your application.
使用服务与控制器/模型的优势在于您不受单个控制器或单个模型的约束。您可以根据应用程序的设计和需求,根据需要创建任意数量的服务。再加上在应用程序的任何类中调用服务的优势。
This goes long, but I would like to show you how I have structured my application:
这很长,但我想向您展示我是如何构建我的应用程序的:
app/
controllers/
MyCompany/
Composers/
Exceptions/
Models/
Observers/
Sanitizers/
ServiceProviders/
Services/
Validators/
views
(...)
I use each folder for a specific function. For example the Validators
directory contains a BaseValidator
class responsible for processing the validation, based on the $rules
and $messages
of specific validators (usually one for each model). I could as easily put this code within a Service, but it makes sense to me to have a specific folder for this even if it is only used within the service (for now).
我将每个文件夹用于特定功能。例如,该Validators
目录包含一个BaseValidator
类负责处理所述验证的基础上,$rules
和$messages
特定验证器(通常为每个模型)。我可以很容易地将此代码放在一个服务中,但对我来说有一个特定的文件夹是有意义的,即使它只在服务中使用(现在)。
I recommend you to read the following articles, as they might explain things a little better to you:
我建议您阅读以下文章,因为它们可能对您解释得更好一些:
Breaking the Mold by Dayle Rees(author of CodeBright): This is where I put it all together, even though I changed a few things to fit my needs.
Breaking the Mold by Dayle Rees(CodeBright 的作者):这就是我把它放在一起的地方,即使我改变了一些东西来满足我的需要。
Decoupling your code in Laravel using Repositories and Servicesby Chris Goosey: This post explains well what is a Service and the Repository Pattern and how they fit together.
Decoupling your code using Repositories and Servicesby Chris Goosey:这篇文章很好地解释了什么是服务和存储库模式以及它们如何组合在一起。
Laracasts also have the Repositories Simplifiedand Single Responsibilitywhich are good resources with practical examples (even though you have to pay).
Laracasts 也有Repositories Simplified和Single Responsibility,它们是带有实际示例的好资源(即使您必须付费)。
回答by Sabrina Leggett
I wanted to post a response to my own question. I could talk about this for days, but I'm going to try to get this posted fast to make sure I get it up.
我想发表对我自己问题的回应。我可以谈论这个好几天,但我会尽量快点把它发布出来,以确保我能把它搞定。
I ended up utilizing the existing structure that Laravel provides, meaning that I kept my files primarily as Model, View, and Controller. I also have a Libraries folder for reusable components that aren't really models.
我最终使用了 Laravel 提供的现有结构,这意味着我将文件主要保存为模型、视图和控制器。我还有一个 Libraries 文件夹,用于存放并非真正模型的可重用组件。
I DID NOT WRAP MY MODELS IN SERVICES/LIBRARIES. All of the reasons provided didn't 100% convince me of the benefit of using services. While I may be wrong, as far as I can see they just result in tons of extra nearly empty files I need to create and switch between when working with models and also really reduce the benefit of using eloquent (especially when it comes to RETRIEVING models, e.g., using pagination, scopes, etc).
我没有将我的模型包装在 SERVICES/LIBRARIES 中。提供的所有理由并不能 100% 说服我使用服务的好处。虽然我可能是错的,但据我所知,它们只会导致大量额外的几乎是空的文件,我需要在使用模型时创建和切换,并且确实减少了使用 eloquent 的好处(尤其是在检索模型时) ,例如,使用分页、范围等)。
I put the business logic IN THE MODELSand access eloquent directly from my controllers. I use a number of approaches to make sure that the business logic doesn't get bypassed:
我将业务逻辑放在模型中,并直接从我的控制器访问 eloquent。我使用多种方法来确保业务逻辑不会被绕过:
- Accessors and mutators:Laravel has great accessors and mutators. If I want to perform an action whenever a post is moved from draft to published I can call this by creating function setIsPublishedAttribute and including the logic in there
- Overriding Create/Update etc:You can always override Eloquent methods in your models to include custom functionality. That way you can call functionality on any CRUD operation. Edit: I think there's a bug with overriding create in newer Laravel versions (so I use events now registered in boot)
- Validation:I hook my validation in the same way, e.g., I'll run validation by overriding CRUD functions and also accessors/mutators if needed. See Esensi or dwightwatson/validating for more information.
- Magic Methods:I use the __get and __set methods of my models to hook into functionality where appropriate
- Extending Eloquent:If there's an action you'd like to take on all update/create you can even extend eloquent and apply it to multiple models.
- Events:This is a straight forward and generally agreed upon place to do this as well. Biggest drawback with events I think is that exceptions are hard to trace (might not be the new case with Laravel's new events system). I also like to group my events by what they do instead of when they are called...e.g., have a MailSender subscriber which listens for events that send mail.
- Adding Pivot/BelongsToMany Events:One of the things I struggled with the longest was how to attach behavior to the modification of belongsToMany relationships. E.g., performing an action whenever a user joins a group. I'm almost done polishing up a custom library for this. I haven't published it yet but it is functional! Will try to post a link soon. EDITI ended up making all my pivots into normal models and my life has been so much easier...
- 访问器和修改器:Laravel 有很棒的访问器和修改器。如果我想在帖子从草稿移动到发布时执行操作,我可以通过创建函数 setIsPublishedAttribute 并在其中包含逻辑来调用它
- 覆盖创建/更新等:您始终可以覆盖模型中的 Eloquent 方法以包含自定义功能。这样您就可以在任何 CRUD 操作上调用功能。编辑:我认为在较新的 Laravel 版本中覆盖 create 存在一个错误(所以我使用现在在引导中注册的事件)
- 验证:我以相同的方式挂钩我的验证,例如,我将通过覆盖 CRUD 函数以及访问器/修改器(如果需要)来运行验证。有关更多信息,请参阅 Esensi 或 dwightwatson/validating。
- 魔术方法:我使用模型的 __get 和 __set 方法在适当的地方挂钩功能
- 扩展 Eloquent:如果您想对所有更新/创建采取行动,您甚至可以扩展 eloquent 并将其应用于多个模型。
- 事件:这是一个直接且普遍同意的地方来做这件事。我认为事件的最大缺点是异常难以追踪(可能不是 Laravel 新事件系统的新情况)。我还喜欢根据事件的作用而不是它们被调用的时间来分组我的事件……例如,有一个 MailSender 订阅者,它侦听发送邮件的事件。
- 添加 Pivot/BelongsToMany 事件:我最苦恼的事情之一是如何将行为附加到belongsToMany 关系的修改中。例如,每当用户加入组时执行操作。我几乎完成了为此完善自定义库。我还没有发布它,但它是功能性的!将尝试尽快发布链接。编辑我最终将所有的支点都变成了普通模型,我的生活变得更加轻松......
Addressing people's concerns with using models:
解决人们对使用模型的担忧:
- Organization:Yes if you include more logic in models, they can be longer, but in general I've found 75% of my models are still pretty small. If I chose to organize the larger ones I can do it using traits (e.g., create a folder for the model with some more files like PostScopes, PostAccessors, PostValidation, etc as needed). I know this is not necessarily what traits are for but this system works without issue.
- 组织:是的,如果您在模型中包含更多逻辑,它们可能会更长,但总的来说,我发现 75% 的模型仍然很小。如果我选择组织较大的,我可以使用特征来完成(例如,根据需要为模型创建一个文件夹,其中包含更多文件,如 PostScopes、PostAccessors、PostValidation 等)。我知道这不一定是特征的用途,但该系统可以正常工作。
Additional Note:I feel like wrapping your models in services is like having a swiss army knife, with lots of tools, and building another knife around it that basically does the same thing? Yeah, sometimes you might want to tape a blade off or make sure two blades are used together...but there are typically other ways to do it...
附加说明:我觉得将您的模型包装在服务中就像拥有一把带有大量工具的瑞士军刀,然后围绕它制造另一把基本上做同样事情的刀?是的,有时您可能想用胶带粘住刀片或确保将两个刀片一起使用……但通常还有其他方法可以做到……
WHEN TO USE SERVICES: This article articulates very well GREAT examples for when to use services (hint: it's not very often). He says basically when your object uses multiple models or models at strange parts of their lifecycleit makes sense. http://www.justinweiss.com/articles/where-do-you-put-your-code/
何时使用服务:这篇文章很好地阐述了何时使用服务的好例子(提示:不是经常使用)。他说基本上当你的对象在生命周期的奇怪部分使用多个模型或模型时,这是有道理的。http://www.justinweiss.com/articles/where-do-you-put-your-code/
回答by Rubens Mariuzzo
What I use to do to create the logic between controllers and models is to create a service layer. Basically, this is my flow for any action within my app:
我用来创建控制器和模型之间的逻辑是创建一个服务层。基本上,这是我的应用程序中任何操作的流程:
- Controller get user's requested action and sent parameters and delegates everything to a service class.
- Service class do all the logic related to the operation: input validation, event logging, database operations, etc...
- Model holds information of fields, data transformation, and definitions of attributes validations.
- 控制器获取用户请求的操作并发送参数并将所有内容委托给服务类。
- 服务类完成与操作相关的所有逻辑:输入验证、事件记录、数据库操作等...
- 模型保存字段、数据转换和属性验证定义的信息。
This is how I do it:
这就是我的做法:
This the method of a controller to create something:
这是控制器创建某些东西的方法:
public function processCreateCongregation()
{
// Get input data.
$congregation = new Congregation;
$congregation->name = Input::get('name');
$congregation->address = Input::get('address');
$congregation->pm_day_of_week = Input::get('pm_day_of_week');
$pmHours = Input::get('pm_datetime_hours');
$pmMinutes = Input::get('pm_datetime_minutes');
$congregation->pm_datetime = Carbon::createFromTime($pmHours, $pmMinutes, 0);
// Delegates actual operation to service.
try
{
CongregationService::createCongregation($congregation);
$this->success(trans('messages.congregationCreated'));
return Redirect::route('congregations.list');
}
catch (ValidationException $e)
{
// Catch validation errors thrown by service operation.
return Redirect::route('congregations.create')
->withInput(Input::all())
->withErrors($e->getValidator());
}
catch (Exception $e)
{
// Catch any unexpected exception.
return $this->unexpected($e);
}
}
This is the service class that does the logic related to the operation:
这是执行与操作相关的逻辑的服务类:
public static function createCongregation(Congregation $congregation)
{
// Log the operation.
Log::info('Create congregation.', compact('congregation'));
// Validate data.
$validator = $congregation->getValidator();
if ($validator->fails())
{
throw new ValidationException($validator);
}
// Save to the database.
$congregation->created_by = Auth::user()->id;
$congregation->updated_by = Auth::user()->id;
$congregation->save();
}
And this is my model:
这是我的模型:
class Congregation extends Eloquent
{
protected $table = 'congregations';
public function getValidator()
{
$data = array(
'name' => $this->name,
'address' => $this->address,
'pm_day_of_week' => $this->pm_day_of_week,
'pm_datetime' => $this->pm_datetime,
);
$rules = array(
'name' => ['required', 'unique:congregations'],
'address' => ['required'],
'pm_day_of_week' => ['required', 'integer', 'between:0,6'],
'pm_datetime' => ['required', 'regex:/([01]?[0-9]|2[0-3]):[0-5]?[0-9]:[0-5][0-9]/'],
);
return Validator::make($data, $rules);
}
public function getDates()
{
return array_merge_recursive(parent::getDates(), array(
'pm_datetime',
'cbs_datetime',
));
}
}
For more information about this way I use to organize my code for a Laravel app: https://github.com/rmariuzzo/Pitimi
有关这种方式的更多信息,我用来组织 Laravel 应用程序的代码:https: //github.com/rmariuzzo/Pitimi
回答by Steve Bauman
In my opinion, Laravel already has many options for you to store your business logic.
在我看来,Laravel 已经为您提供了许多存储业务逻辑的选项。
Short answer:
简短的回答:
- Use laravel's
Request
objects to automatically validate your input, and then persist the data in the request (create the model). Since all of the users input is directly available inthe request, I believe it makes sense to perform this here. - Use laravel's
Job
objects to perform tasks that require individual components, then simply dispatch them. I thinkJob
's encompass service classes. They perform a task, such as business logic.
- 使用 laravel 的
Request
对象自动验证您的输入,然后将数据保存在请求中(创建模型)。由于所有用户输入都可以直接在请求中使用,我相信在这里执行此操作是有意义的。 - 使用 laravel 的
Job
对象来执行需要单独组件的任务,然后简单地调度它们。我认为Job
's 包括服务类。它们执行任务,例如业务逻辑。
Long(er) answer:
长(呃)答案:
Use Respositories When Required:Repositories are bound to be overbloated, and most of the time, are simply used as an accessor
to the model. I feel like they definitely have some use, but unless you're developing a massive application that requiresthat amount of flexibility for you to be able to ditch laravel entirely, stay away from repositories. You'll thank yourself later and your code will be much more straight forward.
需要时使用存储库:存储库必然会过度膨胀,并且在大多数情况下,它只是用作accessor
模型的一个。我觉得它们肯定有一些用处,但是除非您正在开发一个需要足够灵活性才能完全抛弃 laravel的大型应用程序,否则请远离存储库。稍后您会感谢自己,您的代码将更加直接。
Ask yourself if there's a possibility that you're going to be changing PHP frameworks orto a database type that laravel doesn't support.
问问自己是否有可能更改 PHP 框架或Laravel 不支持的数据库类型。
If your answer is "Probably not", then don't implement the repository pattern.
如果您的回答是“可能不是”,则不要实施存储库模式。
In addition to above, please don't slap a pattern on top of a superb ORM like Eloquent. You're just adding complexity that isn't required and it won't benefit you at all.
除了上述之外,请不要在像 Eloquent 这样出色的 ORM 之上添加模式。你只是增加了不必要的复杂性,它根本不会给你带来好处。
Utilize Services sparingly:Service classes to me, are just a place to store business logic to perform a specific task with its given dependencies. Laravel has these out of the box, called 'Jobs', and they have much more flexibility than a custom Service class.
谨慎使用服务:对我来说,服务类只是一个存储业务逻辑的地方,以执行具有给定依赖项的特定任务。Laravel 有这些开箱即用的,称为“作业”,它们比自定义服务类具有更大的灵活性。
I feel like Laravel has a well-rounded solution for the MVC
logic problem. It's just a matter or organization.
我觉得 Laravel 对MVC
逻辑问题有一个全面的解决方案。这只是一个问题或组织。
Example:
例子:
Request:
请求:
namespace App\Http\Requests;
use App\Post;
use App\Jobs\PostNotifier;
use App\Events\PostWasCreated;
use App\Http\Requests\Request;
class PostRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required',
'description' => 'required'
];
}
/**
* Save the post.
*
* @param Post $post
*
* @return bool
*/
public function persist(Post $post)
{
if (!$post->exists) {
// If the post doesn't exist, we'll assign the
// post as created by the current user.
$post->user_id = auth()->id();
}
$post->title = $this->title;
$post->description = $this->description;
// Perform other tasks, maybe fire an event, dispatch a job.
if ($post->save()) {
// Maybe we'll fire an event here that we can catch somewhere else that
// needs to know when a post was created.
event(new PostWasCreated($post));
// Maybe we'll notify some users of the new post as well.
dispatch(new PostNotifier($post));
return true;
}
return false;
}
}
Controller:
控制器:
namespace App\Http\Controllers;
use App\Post;
use App\Http\Requests\PostRequest;
class PostController extends Controller
{
/**
* Creates a new post.
*
* @return string
*/
public function store(PostRequest $request)
{
if ($request->persist(new Post())) {
flash()->success('Successfully created new post!');
} else {
flash()->error('There was an issue creating a post. Please try again.');
}
return redirect()->back();
}
/**
* Updates a post.
*
* @return string
*/
public function update(PostRequest $request, $id)
{
$post = Post::findOrFail($id);
if ($request->persist($post)) {
flash()->success('Successfully updated post!');
} else {
flash()->error('There was an issue updating this post. Please try again.');
}
return redirect()->back();
}
}
In the example above, the request input is automatically validated, and all we need to do is call the persist method and pass in a new Post. I think readability and maintainability should always trump complex and unneeded design patterns.
在上面的例子中,请求输入是自动验证的,我们需要做的就是调用persist方法并传入一个新的Post。我认为可读性和可维护性应该始终胜过复杂和不需要的设计模式。
You can then utilize the exact same persist method for updating posts as well, since we can check whether or not the post already exists and perform alternating logic when needed.
然后,您也可以使用完全相同的持久方法来更新帖子,因为我们可以检查帖子是否已经存在并在需要时执行交替逻辑。