Browse Source

Article CURD code optimization

moell 8 years ago
parent
commit
8ab6b16e8a

+ 28 - 82
app/Http/Controllers/Backend/ArticleController.php

@@ -16,15 +16,20 @@ use App\Services\ArticleService;
 
 class ArticleController extends Controller
 {
-    protected $article;
-
-    protected $tag;
+    /**
+     * @var ArticleService
+     */
+    protected $articleServer;
 
 
-    public function __construct(ArticleRepositoryEloquent $article, TagRepositoryEloquent $tag)
+    /**
+     * ArticleController constructor.
+     *
+     * @param ArticleService $articleService
+     */
+    public function __construct(ArticleService $articleService)
     {
-        $this->article = $article;
-        $this->tag  = $tag;
+        $this->articleServer = $articleService;
     }
 
     /**
@@ -32,18 +37,10 @@ class ArticleController extends Controller
      *
      * @return \Illuminate\Http\Response
      */
-    public function index(ArticleService $articleService, Request $request)
+    public function index(Request $request)
     {
-        $where = ArticleService::backendSearchWhere($request);
-        $articles = $this->article->backendSearchArticle($where);
-        $category   = [];
-        $author     = [];
-        if ($articles) {
-            $data = $articleService->getArticleUserAndCategory($articles);
-            $category   = $data['category'];
-            $author     = $data['user'];
-        }
-        return view('backend.article.index', compact('articles', 'author', 'category'));
+        $articles = $this->articleServer->search($request);
+        return view('backend.article.index', compact('articles'));
     }
 
     /**
@@ -58,28 +55,11 @@ class ArticleController extends Controller
 
     /**
      * @param CreateRequest $request
-     * @param ArticleTagService $articleTagService
      * @return $this|\Illuminate\Http\RedirectResponse
      */
-    public function store(CreateRequest $request, ArticleTagService $articleTagService)
+    public function store(CreateRequest $request)
     {
-        $article = $this->article->create([
-            'title' => $request->title,
-            'content'   => $request->get('markdown-content'),
-            'html_content'   => $request->get('html-content'),
-            'keyword'   => $request->keyword,
-            'desc' => $request->desc,
-            'cate_id'   => $request->cate_id,
-            'user_id'   => Auth::user()->id
-        ]);
-        if ($article) {
-            if ($request->tags != "") {
-                $articleTagService->store($article->id, $request->tags);
-            }
-            return redirect('backend/article')
-                ->with('success', '文章添加成功');
-        }
-        return redirect()->back()->withErrors('系统异常,文章发布失败');
+        return $this->articleServer->store($request);
     }
 
     /**
@@ -94,64 +74,30 @@ class ArticleController extends Controller
     }
 
     /**
-     * Show the form for editing the specified resource.
-     *
-     * @param  int  $id
-     * @return \Illuminate\Http\Response
+     * @param $id
+     * @return $this
      */
-    public function edit($id, ArticleTagService $articleTagService)
+    public function edit($id)
     {
-        $article = $this->article->find($id);
-        $tags = $article->articleTag;
-        $tagIdList = $articleTagService->tagsIdList($tags, false);
-        return view('backend.article.edit', compact('article', 'tagIdList'));
+        return view('backend.article.edit')->with($this->articleServer->edit($id));
     }
 
     /**
-     * Update the specified resource in storage.
-     *
-     * @param  \Illuminate\Http\Request  $request
-     * @param  int  $id
-     * @return \Illuminate\Http\Response
+     * @param UpdateRequest $request
+     * @param $id
+     * @return $this|\Illuminate\Http\RedirectResponse
      */
-    public function update(UpdateRequest $request, $id, ArticleTagService $articleTagService)
+    public function update(UpdateRequest $request, $id)
     {
-        $article = $this->article->find($id);
-        if ($article) {
-            $data = [];
-            $data['title']  = $request->title;
-            $data['desc']   = $request->desc;
-            $data['keyword']    = $request->keyword;
-            $data['cate_id']    = $request->cate_id;
-            $data['content']    = $request->get('markdown-content');
-            $data['html_content']    = $request->get('html-content');
-            if ($this->article->update($data, $id)) {
-                $articleTagService->updateArticleTags($id, $request->tags);
-                return redirect('backend/article')
-                    ->with('success', '文章修改成功');
-            }
-        }
-        return redirect()->back()->withErrors('系统异常,修改文章失败');
+        return $this->articleServer->update($request, $id);
     }
 
     /**
-     * Remove the specified resource from storage.
-     *
-     * @param  int  $id
-     * @return \Illuminate\Http\Response
+     * @param $id
+     * @return \Illuminate\Http\JsonResponse
      */
     public function destroy($id)
     {
-        $article = $this->article->find($id);
-        if ($article) {
-            if ($this->article->delete($id)) {
-                $tags = $article->tags != "" ? explode(',', $article->tags) : "";
-                if (is_array($tags)) {
-                    $this->tag->reduceArticleNumber($tags);
-                }
-                return response()->json(['status' => 0]);
-            }
-        }
-        return response()->json(['status' => 1]);
+        return $this->articleServer->destory($id);
     }
 }

+ 27 - 0
app/Http/routes.php

@@ -12,39 +12,66 @@
 */
 
 Route::get('/', 'HomeController@index');
+
 Route::get('/article/{id}', ['as' => 'article', 'uses' => 'ArticleController@index']);
+
 Route::get('/category/{id}', ['as' => 'category', 'uses' => 'CategoryController@index']);
+
 Route::get('/tag/{id}', ['as' => 'tag', 'uses' => 'TagController@index']);
+
 Route::get('/search', ['as' => 'search', 'uses' => 'SearchController@index']);
+
 Route::get('/page/{alias}', ['as' => 'page.show', 'uses' => 'PageController@index']);
+
 Route::get('/about', ['as' => 'about', 'uses' => 'PageController@about']);
+
 Route::get('/rss', ['as' => 'rss', 'uses'=>'RssController@index']);
 
 Route::group(['prefix'=>'backend'], function(){
 
     Route::get('/login', 'Backend\AuthController@showLoginForm');
+
     Route::post('/login', 'Backend\AuthController@login');
+
     Route::get('/logout', 'Backend\AuthController@logout');
+
     /*Route::get('/register', 'Backend\AuthController@getRegister');
     Route::post('/register', 'Backend\AuthController@postRegister');*/
 
     Route::group(['middleware' => ['auth']], function(){
+
         Route::get('/', ['as' => 'backend.home', 'uses' =>'Backend\HomeController@index']);
+
         Route::resource('article', 'Backend\ArticleController');
+
         Route::resource('category', 'Backend\CategoryController');
+
         Route::get('category/set-nav/{id}', ['as' => 'backend.category.set-nav', 'uses' => 'Backend\CategoryController@setNavigation']);
+
         Route::resource('user', 'Backend\UserController');
+
         Route::resource('tag', 'Backend\TagController');
+
         Route::resource('link', 'Backend\LinkController');
+
         Route::resource('navigation', 'Backend\NavigationController');
+
         Route::resource('page', 'Backend\PageController');
+
         Route::get('system', ['as' => 'backend.system.index', 'uses' => 'Backend\SystemController@index']);
+
         Route::post('system', ['as' => 'backend.system.store', 'uses' => 'Backend\SystemController@store']);
+
         Route::get('upload', ['as' => 'backend.upload.index', 'uses' => 'Backend\UploadController@index']);
+
         Route::delete('file-del', ['as' => 'backend.upload.file-del', 'uses' => 'Backend\UploadController@fileDelete']);
+
         Route::delete('dir-del', ['as' => 'backend.upload.dir-del', 'uses' => 'Backend\UploadController@dirDelete']);
+
         Route::post('mkdir', ['as' => 'backend.upload.mkdir', 'uses' => 'Backend\UploadController@makeDir']);
+
         Route::get('file-upload', ['as' => 'backend.upload.file-upload', 'uses' => 'Backend\UploadController@fileUpload']);
+
         Route::post('file-stroe', ['as' => 'backend.upload.file-store', 'uses' => 'Backend\UploadController@fileStore']);
     });
 });

+ 1 - 1
app/Repositories/ArticleRepositoryEloquent.php

@@ -52,7 +52,7 @@ class ArticleRepositoryEloquent extends BaseRepository implements ArticleReposit
      * @param array $where
      * @return mixed
      */
-    public  function backendSearchArticle(array $where)
+    public function search(array $where)
     {
         if (count($where) > 0) {
             $this->applyConditions($where);

+ 94 - 57
app/Services/ArticleService.php

@@ -2,97 +2,134 @@
 
 namespace App\Services;
 
-use App\Repositories\UserRepositoryEloquent;
-use App\Repositories\CategoryRepositoryEloquent;
-use App\Http\Request;
+use App\Repositories\ArticleRepositoryEloquent;
+use App\Repositories\TagRepositoryEloquent;
+use Illuminate\Http\Request;
+use Auth;
 
 class ArticleService
 {
-    protected $user;
-    protected $category;
 
-    public function __construct(UserRepositoryEloquent $user, CategoryRepositoryEloquent $category)
+    protected $article;
+
+    protected $tag;
+
+    /**
+     * ArticleService constructor.
+     * @param ArticleRepositoryEloquent $article
+     */
+    public function __construct(ArticleRepositoryEloquent $article, TagRepositoryEloquent $tag)
     {
-        $this->user = $user;
-        $this->category = $category;
+        $this->article = $article;
+        $this->tag = $tag;
     }
 
-    public function getArticleUserAndCategory($articles)
+    /**
+     * @param Request $request
+     * @return mixed
+     */
+    public function search(Request $request)
     {
-        $cate_id    = [];
-        $user_id    = [];
-        foreach ($articles as $article) {
-            $cate_id[] = $article->cate_id;
-            $user_id[] = $article->user_id;
+        $where = [];
+        if ($request->has('title')) {
+            $where[] = ['title', 'like', "%".$request->title."%"];
+        }
+
+        if ($request->has('cate_id')) {
+            $where[] = ['cate_id', '=', $request->cate_id];
         }
 
-        return [
-            'category'  => $this->getCategoryIdName($cate_id),
-            'user'      => $this->getUserIdName($user_id)
-        ];
+        return $this->article->with([
+            'user',
+            'category'
+        ])->search($where);
     }
 
     /**
-     * @param array $user
-     * @return array
+     * @param Request $request
+     * @return $this|\Illuminate\Http\RedirectResponse
      */
-    protected function getUserIdName(array $user)
+    public function store(Request $request)
     {
-        if (count($user) > 0) {
-            $users = $this->user->findWhereIn('id', $user, ['id', 'name']);
-            if ($users) {
-                return $this->formatIdName($users->toArray());
-            }
+        $article = $this->article->create(array_merge($this->basicFields($request),[
+            'user_id' => Auth::id()
+        ]));
+        if (!$article) {
+            return redirect()->back()->withErrors('系统异常,文章发布失败');
+        }
+
+        if ($request->has('tags')) {
+            $this->getArticleTagService()->store($article->id, $request->tags);
         }
-        return [];
+
+        return  redirect('backend/article')
+        ->with('success', '文章添加成功');
     }
 
     /**
-     * @param array $category
-     * @return array
+     * @param Request $request
+     * @param $id
+     * @return $this|\Illuminate\Http\RedirectResponse
      */
-    protected function getCategoryIdName(array $category)
+    public function update(Request $request, $id)
     {
-        if (count($category) > 0) {
-            $categories = $this->category->findWhereIn('id', $category, ['id', 'name']);
-            if ($categories) {
-                return $this->formatIdName($categories->toArray());
-            }
+        $article = $this->article->find($id);
+
+        $article->fill($this->basicFields($request));
+        if (!$article->save()) {
+            return redirect()->back()->withErrors('修改文章失败');
         }
-        return [];
+
+        $this->getArticleTagService()->updateArticleTags($id, $request->tags);
+
+        return redirect('backend/article')
+            ->with('success', '文章修改成功');
+
+    }
+
+    public function edit($id)
+    {
+        $article = $this->article->find($id);
+        $tags = $article->articleTag;
+        $tagIdList = $this->getArticleTagService()->tagsIdList($tags, false);
+        return compact('article', 'tagIdList');
     }
 
     /**
-     * @param array $data
-     * @return array
+     * @param $id
+     * @return \Illuminate\Http\JsonResponse
      */
-    protected function formatIdName(array $data)
+    public function destory($id)
     {
-        $new = [];
-        foreach ($data as $d) {
-            $new[$d['id']] = $d['name'];
+        $article = $this->article->find($id);
+
+        if (!$article->delete()) {
+            return response()->json(['status' => 1]);
         }
-        return $new;
+
+        return response()->json(['status' => 0]);
     }
 
+    private function getArticleTagService()
+    {
+        return app('App\Services\ArticleTagService');
+    }
 
     /**
-     * 搜索where条件
-     *
-     * @param $request
+     * @param Request $request
      * @return array
      */
-    public static function backendSearchWhere($request)
+    private function basicFields(Request $request)
     {
-        $where = [];
-        if ($request->title != "") {
-            $where[] = ['title', 'like', "%".$request->title."%"];
-        }
-
-        if ($request->cate_id > 0) {
-            $where[] = ['cate_id', '=', $request->cate_id];
-        }
-
-        return $where;
+        return array_merge($request->intersect([
+            'title',
+            'keyword',
+            'desc',
+            'cate_id',
+            'user_id'
+        ]), [
+            'content' => $request->get('markdown-content'),
+            'html_content' => $request->get('html-conent')
+        ]);
     }
 }

+ 6 - 2
resources/views/backend/article/index.blade.php

@@ -52,13 +52,17 @@
                                 <tr>
                                     <td>{{ $line }}</td>
                                     <td>
-                                        {{ $author[$article->user_id] }}
+                                        @if($article->user)
+                                            {{ $article->user->name }}
+                                        @endif
                                     </td>
                                     <td>{{ $articlePresenter->formatTitle($article->title) }}</td>
                                     <td>{{ $article->read_count }}</td>
                                     <td>{{ $article->comment_count }}</td>
                                     <td>
-                                        {{ $category[$article->cate_id] or '分类已删除' }}
+                                        @if($article->category)
+                                            {{ $article->category->name }}
+                                        @endif
                                     </td>
                                     <td>{{ $article->created_at }}</td>
                                     <td>