1
0
mirror of https://gitee.com/koogua/course-tencent-cloud.git synced 2025-06-25 04:07:17 +08:00

优化代码

This commit is contained in:
xiaochong0302 2020-09-22 16:29:09 +08:00
parent 1f2a5d959b
commit d21e70cb3c
25 changed files with 138 additions and 185 deletions

View File

@ -25,7 +25,9 @@ class HelpList extends Builder
$items = $cache->get(CategoryModel::TYPE_HELP); $items = $cache->get(CategoryModel::TYPE_HELP);
if (!$items) return []; if (empty($items)) {
return [];
}
$result = []; $result = [];

View File

@ -28,7 +28,9 @@ class ImActiveGroupList extends Cache
{ {
$groups = $this->findGroups(); $groups = $this->findGroups();
if (!$groups) return []; if (empty($groups)) {
return [];
}
$result = []; $result = [];

View File

@ -27,7 +27,9 @@ class ImActiveUserList extends Cache
{ {
$users = $this->findUsers($id); $users = $this->findUsers($id);
if (!$users) return []; if (empty($users)) {
return [];
}
$result = []; $result = [];

View File

@ -27,7 +27,9 @@ class ImGroupActiveUserList extends Cache
{ {
$users = $this->findUsers($id); $users = $this->findUsers($id);
if (!$users) return []; if (empty($users)) {
return [];
}
$result = []; $result = [];

View File

@ -11,7 +11,7 @@ class CleanLogTask extends Task
$this->cleanConsoleLog(); $this->cleanConsoleLog();
$this->cleanHttpLog(); $this->cleanHttpLog();
$this->cleanSqlLog(); $this->cleanSqlLog();
$this->cleanListenerLog(); $this->cleanListenLog();
$this->cleanCaptchaLog(); $this->cleanCaptchaLog();
$this->cleanMailLog(); $this->cleanMailLog();
$this->cleanSmsLog(); $this->cleanSmsLog();
@ -57,11 +57,11 @@ class CleanLogTask extends Task
} }
/** /**
* 清理监听日志 * 清理监听日志
*/ */
protected function cleanListenerLog() protected function cleanListenLog()
{ {
$this->cleanLog('listener', 7); $this->cleanLog('listen', 7);
} }
/** /**

View File

@ -8,7 +8,6 @@ class CleanSessionTask extends Task
public function mainAction() public function mainAction()
{ {
$config = $this->getConfig(); $config = $this->getConfig();
$cache = $this->getCache();
$redis = $this->getRedis(); $redis = $this->getRedis();
$redis->select($config->path('session.db')); $redis->select($config->path('session.db'));

View File

@ -12,8 +12,6 @@ class LiveNotifyTask extends Task
public function mainAction() public function mainAction()
{ {
$cache = $this->getCache();
$redis = $this->getRedis(); $redis = $this->getRedis();
$service = new LiveNotifyService(); $service = new LiveNotifyService();

View File

@ -2,48 +2,46 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Library\Cache\Backend\Redis as RedisCache; use App\Services\Service as AppService;
use App\Library\Logger as AppLogger;
use Phalcon\Config as PhConfig;
use Phalcon\Logger\Adapter\File as PhLogger;
class Task extends \Phalcon\Cli\Task class Task extends \Phalcon\Cli\Task
{ {
/**
* @return PhConfig
*/
public function getConfig() public function getConfig()
{ {
return $this->getDI()->getShared('config'); $appService = new AppService();
return $appService->getConfig();
} }
/**
* @return RedisCache
*/
public function getCache() public function getCache()
{ {
return $this->getDI()->getShared('cache'); $appService = new AppService();
return $appService->getCache();
} }
/**
* @return \Redis
*/
public function getRedis() public function getRedis()
{ {
return $this->getCache()->getRedis(); $appService = new AppService();
return $appService->getRedis();
} }
/**
* @param null $channel
* @return PhLogger
*/
public function getLogger($channel = null) public function getLogger($channel = null)
{ {
$logger = new AppLogger(); $appService = new AppService();
return $logger->getInstance($channel); return $appService->getLogger($channel);
}
public function getSettings($section)
{
$appService = new AppService();
return $appService->getLogger($section);
} }
} }

View File

@ -31,12 +31,11 @@ class SessionController extends \Phalcon\Mvc\Controller
$sessionService = new SessionService(); $sessionService = new SessionService();
$captcha = $sessionService->getCaptchaSettings(); $captcha = $sessionService->getSettings('captcha');
if ($this->request->isPost()) { if ($this->request->isPost()) {
$this->checkHttpReferer(); $this->checkHttpReferer();
$this->checkCsrfToken(); $this->checkCsrfToken();
$sessionService->login(); $sessionService->login();

View File

@ -129,7 +129,9 @@ class Package extends Service
public function getGuidingCourses($courseIds) public function getGuidingCourses($courseIds)
{ {
if (!$courseIds) return []; if (empty($courseIds)) {
return [];
}
$courseRepo = new CourseRepo(); $courseRepo = new CourseRepo();

View File

@ -116,7 +116,9 @@ class Role extends Service
*/ */
protected function handleRoutes($routes) protected function handleRoutes($routes)
{ {
if (!$routes) return []; if (empty($routes)) {
return [];
}
$list = []; $list = [];

View File

@ -2,7 +2,6 @@
namespace App\Http\Admin\Services; namespace App\Http\Admin\Services;
use App\Repos\Setting as SettingRepo;
use App\Services\Auth\Admin as AdminAuth; use App\Services\Auth\Admin as AdminAuth;
use App\Validators\Account as AccountValidator; use App\Validators\Account as AccountValidator;
use App\Validators\Captcha as CaptchaValidator; use App\Validators\Captcha as CaptchaValidator;
@ -34,7 +33,7 @@ class Session extends Service
$user = $accountValidator->checkAdminLogin($post['account'], $post['password']); $user = $accountValidator->checkAdminLogin($post['account'], $post['password']);
$captchaSettings = $this->getCaptchaSettings(); $captchaSettings = $this->getSettings('captcha');
/** /**
* 验证码是一次性的,放到最后检查,减少第三方调用 * 验证码是一次性的,放到最后检查,减少第三方调用
@ -54,21 +53,4 @@ class Session extends Service
$this->auth->clearAuthInfo(); $this->auth->clearAuthInfo();
} }
public function getCaptchaSettings()
{
$settingsRepo = new SettingRepo();
$items = $settingsRepo->findBySection('captcha');
$result = [];
if ($items->count() > 0) {
foreach ($items as $item) {
$result[$item->item_key] = $item->item_value;
}
}
return $result;
}
} }

View File

@ -8,9 +8,9 @@ use App\Library\AppInfo as AppInfo;
use App\Library\Seo as Seo; use App\Library\Seo as Seo;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use App\Services\Auth\Home as HomeAuth; use App\Services\Auth\Home as HomeAuth;
use App\Services\Service as AppService;
use App\Traits\Response as ResponseTrait; use App\Traits\Response as ResponseTrait;
use App\Traits\Security as SecurityTrait; use App\Traits\Security as SecurityTrait;
use Phalcon\Config;
use Phalcon\Mvc\Dispatcher; use Phalcon\Mvc\Dispatcher;
class Controller extends \Phalcon\Mvc\Controller class Controller extends \Phalcon\Mvc\Controller
@ -54,7 +54,12 @@ class Controller extends \Phalcon\Mvc\Controller
$this->siteInfo = $this->getSiteInfo(); $this->siteInfo = $this->getSiteInfo();
$this->authUser = $this->getAuthUser(); $this->authUser = $this->getAuthUser();
$this->checkSiteStatus(); if ($this->siteInfo['status'] == 'closed') {
$dispatcher->forward([
'controller' => 'error',
'action' => 'maintain',
]);
}
if ($this->isNotSafeRequest()) { if ($this->isNotSafeRequest()) {
$this->checkHttpReferer(); $this->checkHttpReferer();
@ -111,9 +116,9 @@ class Controller extends \Phalcon\Mvc\Controller
protected function getSiteInfo() protected function getSiteInfo()
{ {
$cache = new SettingCache(); $appService = new AppService();
return $cache->get('site'); return $appService->getSettings('site');
} }
protected function getAppInfo() protected function getAppInfo()
@ -143,23 +148,11 @@ class Controller extends \Phalcon\Mvc\Controller
]; ];
} }
/**
* @return Config
*/
protected function getConfig() protected function getConfig()
{ {
return $this->getDI()->get('config'); $appService = new AppService();
}
protected function checkSiteStatus() return $appService->getConfig();
{
if ($this->siteInfo['status'] == 'closed') {
$this->dispatcher->forward([
'controller' => 'error',
'action' => 'maintain',
'params' => ['message' => $this->siteInfo['closed_tips']],
]);
}
} }
} }

View File

@ -2,6 +2,7 @@
namespace App\Http\Home\Controllers; namespace App\Http\Home\Controllers;
use App\Services\Service as AppService;
use App\Traits\Response as ResponseTrait; use App\Traits\Response as ResponseTrait;
/** /**
@ -72,11 +73,13 @@ class ErrorController extends \Phalcon\Mvc\Controller
*/ */
public function maintainAction() public function maintainAction()
{ {
$message = $this->dispatcher->getParam('message'); $appService = new AppService();
$siteInfo = $appService->getSettings('site');
$this->response->setStatusCode(503); $this->response->setStatusCode(503);
$this->view->setVar('message', $message); $this->view->setVar('message', $siteInfo['closed_tips']);
} }
} }

View File

@ -24,7 +24,9 @@ class Index extends Service
*/ */
$slides = $cache->get(); $slides = $cache->get();
if (!$slides) return []; if (empty($slides)) {
return [];
}
foreach ($slides as $key => $slide) { foreach ($slides as $key => $slide) {

View File

@ -7,7 +7,7 @@ use Phalcon\Db\Profiler as DbProfiler;
use Phalcon\Events\Event as PhEvent; use Phalcon\Events\Event as PhEvent;
use Phalcon\Logger\Adapter\File as FileLogger; use Phalcon\Logger\Adapter\File as FileLogger;
class Profiler extends Listener class Db extends Listener
{ {
/** /**

View File

@ -2,40 +2,26 @@
namespace App\Listeners; namespace App\Listeners;
use App\Caches\Setting as SectionConfigCache; use App\Services\Service as AppService;
use App\Library\Logger as AppLogger;
use Phalcon\Logger\Adapter\File as FileLogger;
use Phalcon\Mvc\User\Plugin as UserPlugin; use Phalcon\Mvc\User\Plugin as UserPlugin;
class Listener extends UserPlugin class Listener extends UserPlugin
{ {
/**
* 获取Logger
*
* @param mixed $channel
* @return FileLogger
*/
public function getLogger($channel = null) public function getLogger($channel = null)
{ {
$logger = new AppLogger(); $appService = new AppService();
$channel = $channel ?: 'listener'; $channel = $channel ?: 'listen';
return $logger->getInstance($channel); return $appService->getLogger($channel);
} }
/**
* 获取某组配置项
*
* @param string $section
* @return array
*/
public function getSettings($section) public function getSettings($section)
{ {
$cache = new SectionConfigCache(); $appService = new AppService();
return $cache->get($section); return $appService->getSettings($section);
} }
} }

View File

@ -2,8 +2,10 @@
namespace App\Providers; namespace App\Providers;
use Phalcon\Config; use App\Listeners\Db as DbListener;
use Phalcon\Config as Config;
use Phalcon\Db\Adapter\Pdo\Mysql as MySqlAdapter; use Phalcon\Db\Adapter\Pdo\Mysql as MySqlAdapter;
use Phalcon\Events\Manager as EventsManager;
class Database extends Provider class Database extends Provider
{ {
@ -35,7 +37,9 @@ class Database extends Provider
$connection = new MySqlAdapter($options); $connection = new MySqlAdapter($options);
if ($config->get('env') == ENV_DEV) { if ($config->get('env') == ENV_DEV) {
$connection->setEventsManager($this->getEventsManager()); $eventsManager = new EventsManager();
$eventsManager->attach('db', new DbListener());
$connection->setEventsManager($eventsManager);
} }
return $connection; return $connection;

View File

@ -2,7 +2,7 @@
namespace App\Providers; namespace App\Providers;
use Phalcon\Events\Manager as PhalconEventsManager; use Phalcon\Events\Manager as PhEventsManager;
class EventsManager extends Provider class EventsManager extends Provider
{ {
@ -15,7 +15,7 @@ class EventsManager extends Provider
$events = require config_path('events.php'); $events = require config_path('events.php');
$eventsManager = new PhalconEventsManager(); $eventsManager = new PhEventsManager();
foreach ($events as $eventType => $handler) { foreach ($events as $eventType => $handler) {
$eventsManager->attach($eventType, new $handler()); $eventsManager->attach($eventType, new $handler());

View File

@ -1,53 +0,0 @@
<?php
namespace App\Repos;
use App\Library\Paginator\Adapter\QueryBuilder as PagerQueryBuilder;
use App\Models\Chapter as ChapterModel;
use App\Models\ChapterLive as ChapterLiveModel;
use App\Models\Course as CourseModel;
use App\Models\CourseUser as CourseUserModel;
use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface;
class Teacher extends Repository
{
public function paginateLiveChapters(array $courseIds, $page = 1, $limit = 15)
{
$startTime = strtotime('today');
$builder = $this->modelsManager->createBuilder()
->columns(['c.id', 'c.title', 'c.course_id', 'cl.start_time', 'cl.end_time'])
->addFrom(ChapterModel::class, 'c')
->join(ChapterLiveModel::class, 'c.id = cl.chapter_id', 'cl')
->inWhere('cl.course_id', $courseIds)
->andWhere('cl.start_time > :start_time:', ['start_time' => $startTime])
->orderBy('cl.start_time ASC');
$pager = new PagerQueryBuilder([
'builder' => $builder,
'page' => $page,
'limit' => $limit,
]);
return $pager->paginate();
}
/**
* @param int $userId
* @return ResultsetInterface|Resultset|CourseModel[]
*/
public function findLiveCourses($userId)
{
return $this->modelsManager->createBuilder()
->columns('c.*')
->addFrom(CourseModel::class, 'c')
->join(CourseUserModel::class, 'c.id = cu.course_id', 'cu')
->where('cu.user_id = :user_id:', ['user_id' => $userId])
->andWhere('cu.role_type = :role_type:', ['role_type' => CourseUserModel::ROLE_TEACHER])
->andWhere('c.model = :model:', ['model' => CourseModel::MODEL_LIVE])
->getQuery()->execute();
}
}

46
app/Repos/TeacherLive.php Normal file
View File

@ -0,0 +1,46 @@
<?php
namespace App\Repos;
use App\Library\Paginator\Adapter\QueryBuilder as PagerQueryBuilder;
use App\Models\Chapter as ChapterModel;
use App\Models\ChapterLive as ChapterLiveModel;
use App\Models\Course as CourseModel;
use App\Models\CourseUser as CourseUserModel;
class TeacherLive extends Repository
{
public function paginate($userId, $page = 1, $limit = 15)
{
$columns = [
'course_id' => 'course.id',
'course_title' => 'course.title',
'chapter_id' => 'chapter.id',
'chapter_title' => 'chapter.title',
'live_start_time' => 'cl.start_time',
'live_end_time' => 'cl.end_time',
];
$builder = $this->modelsManager->createBuilder()
->columns($columns)
->addFrom(ChapterModel::class, 'chapter')
->join(ChapterLiveModel::class, 'chapter.id = cl.chapter_id', 'cl')
->join(CourseModel::class, 'chapter.course_id = course.id', 'course')
->join(CourseUserModel::class, 'course.id = cu.course_id', 'cu')
->where('cu.user_id = :user_id:', ['user_id' => $userId])
->andWhere('cu.role_type = :role_type:', ['role_type' => CourseUserModel::ROLE_TEACHER])
->andWhere('course.model = :model:', ['model' => CourseModel::MODEL_LIVE])
->andWhere('cl.start_time > :start_time:', ['start_time' => strtotime('today')])
->orderBy('cl.start_time ASC');
$pager = new PagerQueryBuilder([
'builder' => $builder,
'page' => $page,
'limit' => $limit,
]);
return $pager->paginate();
}
}

View File

@ -55,7 +55,7 @@ class Admin extends AuthService
{ {
$authUser = $this->getAuthInfo(); $authUser = $this->getAuthInfo();
if ($authUser['root']) { if ($authUser['root'] == 1) {
return true; return true;
} }

View File

@ -3,7 +3,7 @@
namespace App\Services\Logic\Teacher\Console; namespace App\Services\Logic\Teacher\Console;
use App\Library\Paginator\Query as PagerQuery; use App\Library\Paginator\Query as PagerQuery;
use App\Repos\Teacher as TeacherRepo; use App\Repos\TeacherLive as TeacherLiveRepo;
use App\Services\Logic\Service; use App\Services\Logic\Service;
class LiveList extends Service class LiveList extends Service
@ -13,31 +13,14 @@ class LiveList extends Service
{ {
$user = $this->getLoginUser(); $user = $this->getLoginUser();
$teacherRepo = new TeacherRepo(); $teacherLiveRepo = new TeacherLiveRepo();
$courses = $teacherRepo->findLiveCourses($user->id);
if ($courses->count() == 0) {
return [];
}
$courseMapping = [];
foreach ($courses as $course) {
$courseMapping[$course->id] = [
'id' => $course->id,
'title' => $course->title,
];
}
$courseIds = kg_array_column($courses->toArray(), 'id');
$pagerQuery = new PagerQuery(); $pagerQuery = new PagerQuery();
$page = $pagerQuery->getPage(); $page = $pagerQuery->getPage();
$limit = $pagerQuery->getLimit(); $limit = $pagerQuery->getLimit();
$pager = $teacherRepo->paginateLiveChapters($courseIds, $page, $limit); $pager = $teacherLiveRepo->paginate($user->id, $page, $limit);
if ($pager->total_items == 0) { if ($pager->total_items == 0) {
return $pager; return $pager;
@ -47,13 +30,16 @@ class LiveList extends Service
foreach ($pager->items as $item) { foreach ($pager->items as $item) {
$items[] = [ $items[] = [
'course' => $courseMapping[$item->course_id], 'course' => [
'chapter' => [ 'id' => $item->course_id,
'id' => $item->id, 'title' => $item->course_title,
'title' => $item->title,
], ],
'start_time' => $item->start_time, 'chapter' => [
'end_time' => $item->end_time, 'id' => $item->chapter_id,
'title' => $item->chapter_title,
],
'start_time' => $item->live_start_time,
'end_time' => $item->live_end_time,
]; ];
} }

View File

@ -1,11 +1,9 @@
<?php <?php
use App\Listeners\Pay; use App\Listeners\Pay;
use App\Listeners\Profiler;
use App\Listeners\UserDailyCounter; use App\Listeners\UserDailyCounter;
return [ return [
'db' => Profiler::class,
'pay' => Pay::class, 'pay' => Pay::class,
'userDailyCounter' => UserDailyCounter::class, 'userDailyCounter' => UserDailyCounter::class,
]; ];

View File

@ -17,7 +17,7 @@ html {
.kg-tips .message { .kg-tips .message {
margin-top: 20px; margin-top: 20px;
color: #666; font-size: 18px;
} }
.kg-tips .layui-text { .kg-tips .layui-text {