Home Backend Development PHP Tutorial Detailed explanation of examples of activerecord and activecontroller in Yii2

Detailed explanation of examples of activerecord and activecontroller in Yii2

Aug 23, 2017 am 10:14 AM
activerecord 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 = &#39;app\models\db\Task&#39;;

    public function actions()
    {
        $actions = parent::actions();
        unset($actions[&#39;index&#39;]);

        return $actions;
    }

    public function actionIndex()
    {
        $searchModel = new TaskSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $dataProvider;
    }
}
Copy after login

这里调用的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 [
            [[&#39;projectId&#39;, &#39;keyword&#39;], &#39;string&#39;],
            [&#39;main_type&#39;, &#39;in&#39;, &#39;range&#39; => self::getEnumColumnValues(&#39;main_type&#39;)],
            [&#39;type&#39;, &#39;in&#39;, &#39;range&#39; => self::getEnumColumnValues(&#39;type&#39;)],
            [&#39;_status&#39;, &#39;in&#39;, &#39;range&#39; => self::getEnumColumnValues(&#39;_status&#39;)],
            [&#39;publish_status&#39;, &#39;in&#39;, &#39;range&#39; => self::getEnumColumnValues(&#39;publish_status&#39;)],
        ];
    }

    /**
     * @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, &#39;&#39;);

        if (!$this->validate()) {
            return (new \yii\rest\Serializer())->serialize($this);
        }

        $query = Task::find();

        $dataProvider = new ActiveDataProvider([
            &#39;query&#39; => $query,
            &#39;pagination&#39; => [
                &#39;defaultPageSize&#39; => self::DEFAULT_PAGE_SIZE,
                &#39;pageSizeParam&#39; => &#39;page_size&#39;,
                &#39;pageSizeLimit&#39; => [0, 100],
            ],
        ]);

        $query->andFilterWhere([
            &#39;projectId&#39; => $this->projectId,
            &#39;main_type&#39; => $this->main_type,
            &#39;type&#39; => $this->type,
            &#39;_status&#39; => $this->_status,
            &#39;publish_status&#39; => $this->publish_status,
        ]);
        $query
            ->andFilterWhere([&#39;like&#39;, &#39;name&#39;, $this->keyword]);

        return $dataProvider;
    }

}
Copy after login

这里面的

$this->load($params, &#39;&#39;);
Copy after login

需要加上第二个参数,因为和activeform的表单提交不同,这里的输入只是一维数组而不是两维。

&#39;defaultPageSize&#39; => self::DEFAULT_PAGE_SIZE
Copy after login

默认的每页记录数(querystring内没有提供的情况下),如果没有这行,Yii2给的默认值是20

&#39;pageSizeParam&#39; => &#39;page_size&#39;
Copy after login

每页记录数的querystring名称,默认是'per-page'。

&#39;pageSizeLimit&#39; => [0, 100]
Copy after login

如果page_size=0表示无分页限制,取出所有的纪录。这个值默认是[1, 50],防止page_size过大影响性能。

if (!$this->validate()) {
    return (new \yii\rest\Serializer())->serialize($this);}
Copy after login

这一段可以直接格式化输出错误内容,并且将Http status code改成4xx(表示客户端错误)。

使用的时候发现一些问题

mongodb的objectId并不是纯数字,put/get one/delete方法会报404错误,所以yii的路由规则要加上一段,类似:


[&#39;class&#39; => &#39;yii\rest\UrlRule&#39;, &#39;controller&#39; => [&#39;rest/v2/tasklogs&#39; => &#39;rest-v2/task-log&#39;], &#39;tokens&#39; => [&#39;{id}&#39; => &#39;<id:\\w[\\w,]*>&#39;]],
Copy after login

存日期类型的话要像下面一样


$this->_created = new \MongoDate(); // yii2-mongodb v2.0.x

$this->_created = new \Mongodb\BSON\UTCDateTime(round(microtime(true))*1000); // yii2-mongodb v2.1.x
Copy after login

输出显示的时候


$this->_created = $this->_created->toDateTime()->setTimezone(new \DateTimeZone(&#39;Asia/Shanghai&#39;))->format("Y-m-d H:i:s");
Copy after login

attributes和rules方法,attributes表示查询后输出显示的字段,rules里面控制的是输入验证的字段:


    /**
     * @inheritdoc
     */
    public function attributes()
    {
        return [&#39;_id&#39;, &#39;message&#39;, &#39;data&#39;, &#39;_created&#39;, &#39;_updated&#39;];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[&#39;message&#39;, &#39;data&#39;], &#39;safe&#39;],
        ];
    }
Copy after login

page_size值等于0的时候,只返回一条记录,而不是所有,这里有个bug

yii2-mongodb/Command.php下面(目前版本v2.1.2),603行

if ($options[&#39;limit&#39;] === null) {
Copy after login

应该改成

if ($options[&#39;limit&#39;] === -1) {
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

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 permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

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...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

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�...

See all articles