Home > Article > PHP Framework > What is the difference between model and activeRecord in yii2
The difference between model and activeRecord (AR for short) in Yii2 is analyzed as follows:
(Related recommendations: yii)
1. Model
models are part of mvc and are objects that represent business data, rules and logic. The Model class is also the base class for more advanced models such as Active Record
By default, the model inherits directly from yii\base\Model.
namespace app\models; use yii\base\Model; class LoginForm extends Model { public $username; public $password; public function rules() { // 这里写你的验证规则 [['username', 'password'], 'required'], // password is validated by validatePassword() ['password', 'checkPassword'], // 验证密码 } // 这里写你验证密码的逻辑 public function checkPassword($attribute,$params) { // ...... } // 这里写登录的逻辑 public function login() { // ...... } }
Let’s look at the controller code:
namespace app\controllers; use Yii; use yii\web\Controller; class SiteController extends Controller { // ... public function actionLogin() { $model = new LoginForm(); // 根据用户在登录表单的输入来做判断 if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->goBack(); } } }
2. ActiveRecord class
Active Record (hereinafter referred to as AR) provides an object-oriented interface for accessing data in the database. An activeRecord class is associated with a data table. Each activeRecord object corresponds to a row in the table, and the object's attributes (that is, the attribute Attribute of AR) are mapped to the corresponding columns of the data row. An activity record (AR object) corresponds to a row of the data table, and the attributes of the AR object map the corresponding columns of the row.
3. The relationship between Model and ActiveRecord class
You can see it in yii\db\ActiveRecord.php
class ActiveRecord extends BaseActiveRecord { ... }
You can see it in yii\db\BaseActiveRecord.php to
abstract BaseActiveRecord extends Model implements ActiveRecordInterface { ... }
The above is the detailed content of What is the difference between model and activeRecord in yii2. For more information, please follow other related articles on the PHP Chinese website!