ArticleController.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/2/24
  6. * Time: 下午12:48
  7. */
  8. namespace frontendApi\modules\v1\controllers;
  9. use common\models\Article;
  10. use common\models\ArticleCategory;
  11. class ArticleController extends BaseController
  12. {
  13. public $modelClass = Article::class;
  14. /**
  15. * 返回所有分类并带5条新闻
  16. * @return mixed
  17. * @throws \yii\web\HttpException
  18. */
  19. public function actionIndex(){
  20. $news=ArticleCategory::find()->select('ID,CATE_NAME')->asArray()->all();
  21. foreach ($news as &$value){
  22. $value['LISTS']=Article::find()->select('ID,TITLE,CID,CREATED_AT')->where('CID=:CID AND STATUS=1',[':CID'=>$value['ID']])->orderBy('CREATED_AT DESC')->limit(5)->asArray()->all();
  23. }
  24. return static::notice($news);
  25. }
  26. /**
  27. * 文章分类
  28. * @return mixed
  29. * @throws \yii\web\HttpException
  30. */
  31. public function actionCategory(){
  32. return static::notice(ArticleCategory::getAllCategory());
  33. }
  34. /**文章前10条列表
  35. * @return mixed
  36. * @throws \yii\web\HttpException
  37. */
  38. public function actionGetNewArticle(){
  39. $data = Article::find()->select('ID,TITLE,CID,CREATED_AT')->where('STATUS=1')->orderBy('CREATED_AT DESC')->limit(10)->asArray()->all();
  40. return static::notice($data);
  41. }
  42. /**
  43. * 文章列表
  44. * @return mixed
  45. * @throws \yii\web\HttpException
  46. */
  47. public function actionList(){
  48. $cid = \Yii::$app->request->get('cid');
  49. $condition = ' AND STATUS=1';
  50. $params = [];
  51. if($cid){
  52. $condition .= ' AND CID=:CID';
  53. $params[':CID'] = $cid;
  54. }
  55. $data = Article::lists($condition, $params, [
  56. 'select' => 'ID,TITLE,CID,CREATED_AT',
  57. 'orderBy' => 'CREATED_AT DESC',
  58. 'useSlaves' => true,
  59. ]);
  60. // 全部分类
  61. $data['allCategory'] = ArticleCategory::getAllCategory();
  62. return static::notice($data);
  63. }
  64. /**
  65. * 获取文章详细
  66. * @return mixed
  67. * @throws \yii\web\HttpException
  68. */
  69. public function actionDetail(){
  70. $id = \Yii::$app->request->get('id');
  71. $data = null;
  72. if($id){
  73. $data = Article::findOneAsArray('ID=:ID AND STATUS=1', [':ID'=>$id], 'ID,TITLE,CID,CREATED_AT');
  74. }
  75. if($data){
  76. // 暂时先从文件中取内容
  77. $path = \Yii::getAlias('@common/runtime/articleContent/').$data['ID'];
  78. if(!file_exists($path)){
  79. $data['CONTENT'] = '';
  80. } else {
  81. $data['CONTENT'] = file_get_contents($path);
  82. }
  83. return static::notice($data);
  84. } else {
  85. return static::notice('文章不存在', 400);
  86. }
  87. }
  88. }