


Detailed explanation of examples of activerecord and activecontroller in Yii2
一些补充
activecontroller的各种action是可以重载的,但必须先要unset掉父类的方法。
比如下面这样,注意里面的actions()方法,如果这里没有unset掉父类方法的话,重载的function actionXXX不会起作用。
<?php namespace app\modules\rest\v2\controllers; use Yii; use yii\data\ActiveDataProvider; use app\models\db\Task; use app\models\db\TaskSearch; class TaskController extends BaseActiveController { public $modelClass = 'app\models\db\Task'; public function actions() { $actions = parent::actions(); unset($actions['index']); return $actions; } public function actionIndex() { $searchModel = new TaskSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $dataProvider; } }
这里调用的TaskSearch类仿照了gii生成的ModelSearch类,TaskSearch类的代码
<?php namespace app\models\db; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use app\models\db\Task; class TaskSearch extends Task { public $keyword; /** * @inheritdoc */ public function rules() { return [ [['projectId', 'keyword'], 'string'], ['main_type', 'in', 'range' => self::getEnumColumnValues('main_type')], ['type', 'in', 'range' => self::getEnumColumnValues('type')], ['_status', 'in', 'range' => self::getEnumColumnValues('_status')], ['publish_status', 'in', 'range' => self::getEnumColumnValues('publish_status')], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $this->load($params, ''); if (!$this->validate()) { return (new \yii\rest\Serializer())->serialize($this); } $query = Task::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'defaultPageSize' => self::DEFAULT_PAGE_SIZE, 'pageSizeParam' => 'page_size', 'pageSizeLimit' => [0, 100], ], ]); $query->andFilterWhere([ 'projectId' => $this->projectId, 'main_type' => $this->main_type, 'type' => $this->type, '_status' => $this->_status, 'publish_status' => $this->publish_status, ]); $query ->andFilterWhere(['like', 'name', $this->keyword]); return $dataProvider; } }
这里面的
$this->load($params, '');
需要加上第二个参数,因为和activeform的表单提交不同,这里的输入只是一维数组而不是两维。
'defaultPageSize' => self::DEFAULT_PAGE_SIZE
默认的每页记录数(querystring内没有提供的情况下),如果没有这行,Yii2给的默认值是20
'pageSizeParam' => 'page_size'
每页记录数的querystring名称,默认是'per-page'。
'pageSizeLimit' => [0, 100]
如果page_size=0表示无分页限制,取出所有的纪录。这个值默认是[1, 50],防止page_size过大影响性能。
if (!$this->validate()) { return (new \yii\rest\Serializer())->serialize($this);}
这一段可以直接格式化输出错误内容,并且将Http status code改成4xx(表示客户端错误)。
使用的时候发现一些问题
mongodb的objectId并不是纯数字,put/get one/delete方法会报404错误,所以yii的路由规则要加上一段,类似:
['class' => 'yii\rest\UrlRule', 'controller' => ['rest/v2/tasklogs' => 'rest-v2/task-log'], 'tokens' => ['{id}' => '<id:\\w[\\w,]*>']],
存日期类型的话要像下面一样
$this->_created = new \MongoDate(); // yii2-mongodb v2.0.x $this->_created = new \Mongodb\BSON\UTCDateTime(round(microtime(true))*1000); // yii2-mongodb v2.1.x
输出显示的时候
$this->_created = $this->_created->toDateTime()->setTimezone(new \DateTimeZone('Asia/Shanghai'))->format("Y-m-d H:i:s");
attributes和rules方法,attributes表示查询后输出显示的字段,rules里面控制的是输入验证的字段:
/** * @inheritdoc */ public function attributes() { return ['_id', 'message', 'data', '_created', '_updated']; } /** * @inheritdoc */ public function rules() { return [ [['message', 'data'], 'safe'], ]; }
page_size值等于0的时候,只返回一条记录,而不是所有,这里有个bug
yii2-mongodb/Command.php下面(目前版本v2.1.2),603行
if ($options['limit'] === null) {
应该改成
if ($options['limit'] === -1) {
The above is the detailed content of Detailed explanation of examples of activerecord and activecontroller in Yii2. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
