想建一个仓库存储一下这些代码,专门存储一些有用的代码片段,或者重构前和重构后的代码。 害怕遇到这样子的代码!!! 举个栗子:
class ArticleController { public function index(Request $request) { $ids = $request->input('ids'); // 得到的是字符串数组,转成整型 ['2', '4', '6'] foreach ($ids as &$id) { $id = intval($id); } $articles = Article::whereIn($ids)->get(); return $articles; } // 用原生 PHP 函数减少代码量 public function resonIndex(Request $request) { $ids = $request->input('ids'); // 得到的是字符串数组,转成整型 ['2', '4', '6'] $ids = array_map('intval', $ids); $articles = Article::whereIn($ids)->get(); return $articles; } }
class ArticleController { public function store(Request $request) { $articleData = $request->only(['title', 'type', 'body']); // 普通文章 if ($articleData['type'] == 1) { // do something } // 视频文章 elseif ($article['type'] == 2) { // do something } // 图片文章 elseif ($article['type'] == 3) { // do something } else { // 默认存储普通文章 } return back()->with('status', '创建完成'); } }
<?php class ArticleController { // 文章类型对应的方法 protected $typeMethods = [ 'storeCommonArticle', 'storeVideoArticle', 'storePictureArticle' ]; public function store(Request $request) { $type = $request->input('type'); $method = $this->typeMethods[$type] ?? array_shift($this->typeMethods); // 动态分类处理 $this->$method($request); return back()->with('status', '创建完成'); } /** * 普通文章的存储 */ protected function storeCommonArticle() { // do something } /** * 视频文章的存储 */ protected function storeVideoArticle() { } /** * 图片文章的创建 */ protected function storePictureArticle() { } }
大伙都来秀一下自己见过或者用过的优秀代码。
![]() | 1 mcfog 2018-05-02 11:09:23 +08:00 然而例子的代码质量并不高 |
![]() | 2 DavidNineRoc OP @mcfog 嗯,所以亮出你的代码吧 |
3 kslr 2018-05-02 13:27:51 +08:00 文章类型应该交给 model,验证用 validation 把所有拆分开。这样既灵活,也能用事件等等。感觉楼主这样用和直接手写 PHP 有什么区别 |
4 kslr 2018-05-02 13:31:42 +08:00 我个人的习惯是所有定义为资源控制器,根据接口操作数据,如果有分类就添加一对多关联等等。 像文章类型都在模型内部转换好 |
![]() | 5 murmur 2018-05-02 13:35:25 +08:00 ![]() 一般都是直接找成组的 util 代码收集多了 自己的 util 也快赶上别人的 util 了 |
![]() | 6 DavidNineRoc OP |
7 jacobma 2018-05-02 19:27:27 +08:00 via Android 觉得第一个代码其实挺好的 |
8 kslr 2018-05-02 23:31:43 +08:00 via Android @DavidNineRoc 你没理解我的意思吧,大体就是和纯手撸没有区别 |