Yii Tutorial PDF Version Quick Guide Resources Job Search Discussion The Yii[ji:] framework is an open-source PHP framework for rapidly-developing, modern Web applications. It is built around the Model-View-Controller composite pattern. Yii provides secure and professional features to create robust projects rapidly. Audience The Yii framework has a component-based architecture and a full solid caching support. Therefore, it is suitable for building all kinds of Web applications: forums, portals, content managements systems, RESTful services, e-commerce websites, and so forth. Prerequisites Yii is a pure OOP (Object-Oriented Programming) framework. Hence, it requires a basic knowledge of OOP. The Yii framework also uses the latest features of PHP, like traits and namespaces. The major requirements for Yii2 are PHP 5.4+ and a web server. Print Page Previous Next Advertisements ”;
Category: yii
Yii – Rules of URL
Yii – Rules of URL ”; Previous Next A URL rule is an instance if yiiwebUrlRule. The urlManager components uses the URL rules declared in its rules property when the pretty URL format is enabled. To parse a request, the URL manager obtains the rules in the order they are declared and looks for the first rule. Step 1 − Modify the urlManager component in the config/web.php file. ”urlManager” => [ ”showScriptName” => false, ”enablePrettyUrl” => true, ”rules” => [ ”about” => ”site/about”, ] ], Step 2 − Go to your web browser at http://localhost:8080/about, you will see the about page. A URL rule can be associated with query parameters in this pattern − <ParamName:RegExp>, where − ParamName − The parameter name RegExp − An optional regular expression used to match parameter values Suppose, we have declared the following URL rules − [ ”articles/<year:d{4}>/<category>” => ”article/index”, ”articles” => ”article/index”, ”article/<id:d+>” => ”article/view”, ] When the rules are used for parsing − /index.php/articles is parsed into the article/index /index.php/articles/2014/php is parsed into the article/index /index.php/article/100 is parsed into the article/view /index.php/articles/php is parsed into articles/php When the rules are used for creating URLs − Url::to([”article/index”]) creates /index.php/articles Url::to([”article/index”, ”year” => 2014, ”category” => ”php”]) creates /index.php/articles/2014/php Url::to([”article/view”, ”id” => 100]) creates /index.php/article/100 Url::to([”article/view”, ”id” => 100, ”source” => ”ad”]) creates /index.php/article/100?source=ad Url::to([”article/index”, ”category” => ”php”]) creates /index.php/article/index?category=php To add a suffix to the URL, you should configure the yiiwebUrlManager::$suffix property. Step 3 − Modify the urlComponent in the config/web.php file. ”urlManager” => [ ”showScriptName” => false, ”enablePrettyUrl” => true, ”enableStrictParsing” => true, ”suffix” => ”.html” ], Step 4 − Type the address http://localhost:8080/site/contact.html in the address bar of the web browser and you will see the following on your screen. Notice the html suffix. Print Page Previous Next Advertisements ”;
Yii – Data Access Objects
Yii – Data Access Objects ”; Previous Next To execute an SQL query, you should follow these steps − Create an yiidbCommand with an SQL query. Bind parameters (not required) Execute the command. Step 1 − Create a function called actionTestDb in the SiteController. public function actionTestDb(){ // return a set of rows. each row is an associative array of column names and values. // an empty array is returned if the query returned no results $users = Yii::$app->db->createCommand(”SELECT * FROM user LIMIT 5”) ->queryAll(); var_dump($users); // return a single row (the first row) // false is returned if the query has no result $user = Yii::$app->db->createCommand(”SELECT * FROM user WHERE id=1”) ->queryOne(); var_dump($user); // return a single column (the first column) // an empty array is returned if the query returned no results $userName = Yii::$app->db->createCommand(”SELECT name FROM user”) ->queryColumn(); var_dump($userName); // return a scalar value // false is returned if the query has no result $count = Yii::$app->db->createCommand(”SELECT COUNT(*) FROM user”) ->queryScalar(); var_dump($count); } The above example shows various ways of fetching data from a DB. Step 2 − Go to the address http://localhost:8080/index.php?r=site/test-db, you will see the following output. Create an SQL Command To create an SQL command with parameters, you should always use the approach of binding parameters to prevent the SQL injection. Step 1 − Modify the actionTestDb method this way. public function actionTestDb() { $firstUser = Yii::$app->db->createCommand(”SELECT * FROM user WHERE id = :id”) ->bindValue(”:id”, 1) ->queryOne(); var_dump($firstUser); $params = [”:id” => 2, ”:name” => ”User2”]; $secondUser = Yii::$app->db->createCommand(”SELECT * FROM user WHERE id = :id AND name = :name”) ->bindValues($params) ->queryOne(); var_dump($secondUser); //another approach $params = [”:id” => 3, ”:name” => ”User3”]; $thirdUser = Yii::$app->db->createCommand(”SELECT * FROM user WHERE id = :id AND name = :name”, $params) ->queryOne(); var_dump($thirdUser); } In the code above − bindValue() − binds a single parameter value. bindValues() − binds multiple parameter values. Step 2 − If you go to the address http://localhost:8080/index.php?r=site/test-db, you will see the following output. INSERT, UPDATE and DELETE Queries For INSERT, UPDATE, and DELETE queries, you may call insert(), update(), and delete() methods. Step 1 − Modify the actionTestDb method this way. public function actionTestDb() { public function actionTestDb(){ // INSERT (table name, column values) Yii::$app->db->createCommand()->insert(”user”, [ ”name” => ”My New User”, ”email” => ”[email protected]”, ])->execute(); $user = Yii::$app->db->createCommand(”SELECT * FROM user WHERE name = :name”) ->bindValue(”:name”, ”My New User”) ->queryOne(); var_dump($user); // UPDATE (table name, column values, condition) Yii::$app->db->createCommand()->update(”user”, [”name” => ”My New User Updated”], ”name = “My New User””)->execute(); $user = Yii::$app->db->createCommand(”SELECT * FROM user WHERE name = :name”) ->bindValue(”:name”, ”My New User Updated”) ->queryOne(); var_dump($user); // DELETE (table name, condition) Yii::$app->db->createCommand()->delete(”user”, ”name = “My New User Updated””)->execute(); $user = Yii::$app->db->createCommand(”SELECT * FROM user WHERE name = :name”) ->bindValue(”:name”, ”My New User Updated”) ->queryOne(); var_dump($user); } } Step 2 − Type the URL http://localhost:8080/index.php?r=site/test-db in the address bar of the web browser and you will see the following output. Print Page Previous Next Advertisements ”;
Yii – Active Record
Yii – Active Record ”; Previous Next Active Record provides an object-oriented API for accessing data. An Active Record class is associated with a database table. Yii provides the Active Record support for the following relational databases − MySQL 4.1 or later SQLite 2 and 3: PostgreSQL 7.3 or later Microsoft SQL Server 2008 or later CUBRID 9.3 or later Oracle ElasticSearch Sphinx Additionally, the Active Record class supports the following NoSQL databases − Redis 2.6.12 or later MongoDB 1.3.0 or later After declaring an Active Record class(MyUser model in our case) for a separate database table, you should follow these steps to query data from it − Create a new query object, using the yiidbActiveRecord::find() method. Build the query object. Call a query method to retrieve data. Step 1 − Modify the actionTestDb() method this way. public function actionTestDb() { // return a single user whose ID is 1 // SELECT * FROM `user` WHERE `id` = 1 $user = MyUser::find() ->where([”id” => 1]) ->one(); var_dump($user); // return the number of users // SELECT COUNT(*) FROM `user` $users = MyUser::find() ->count(); var_dump($users); // return all users and order them by their IDs // SELECT * FROM `user` ORDER BY `id` $users = MyUser::find() ->orderBy(”id”) ->all(); var_dump($users); } The code given above shows how to use ActiveQuery to query data. Step 2 − Go to http://localhost:8080/index.php?r=site/test-db, you will see the following output. Querying by primary key values or a set of column values is a common task, that is why Yii provides the following methods − yiidbActiveRecord::findOne() − Returns a single Active Record instance yidbActiveRecord::findAll() − Returns an array of Active Record instances Example − public function actionTestDb() { // returns a single customer whose ID is 1 // SELECT * FROM `user` WHERE `id` = 1 $user = MyUser::findOne(1); var_dump($user); // returns customers whose ID is 1,2,3, or 4 // SELECT * FROM `user` WHERE `id` IN (1,2,3,4) $users = MyUser::findAll([1, 2, 3, 4]); var_dump($users); // returns a user whose ID is 5 // SELECT * FROM `user` WHERE `id` = 5 $user = MyUser::findOne([ ”id” => 5 ]); var_dump($user); } Save Data to Database To save data to the database, you should call the yiidbActiveRecord::save() method. Step 1 − Modify the actionTestDb() method this way. public function actionTestDb() { // insert a new row of data $user = new MyUser(); $user->name = ”MyCustomUser2”; $user->email = ”[email protected]”; $user->save(); var_dump($user->attributes); // update an existing row of data $user = MyUser::findOne([”name” => ”MyCustomUser2”]); $user->email = ”[email protected]”; $user->save(); var_dump($user->attributes); } Step 2 − Go to http://localhost:8080/index.php?r=site/test-db, you will see the following output. To delete a single row of data, you should − Retrieve the Active Record instance Call the yiidbActiveRecord::delete() method Step 1 − Modify the actionTestDb() method this way. public function actionTestDb() { $user = MyUser::findOne(2); if($user->delete()) { echo “deleted”; } } Step 2 − Type http://localhost:8080/index.php?r=site/test-db in the address bar of the web browser, you will see the following output. Step 3 − You can also call the yiidbActiveRecord::deleteAll() method to delete multiple rows of data, for example. public function actionTestDb() { MyUser::deleteAll(”id >= 20”); } Print Page Previous Next Advertisements ”;
Yii – RESTful APIs in Action
Yii – RESTful APIs in Action ”; Previous Next The controller class extends from the yiirestActiveController class, which implements common RESTful actions. We specify the $modelClass property so that the controller knows which model to use for manipulating data. Step 1 − Create a file called UserController.php inside the controllers folder. <?php namespace appcontrollers; use yiirestActiveController; class UserController extends ActiveController { public $modelClass = ”appmodelsMyUser”; } ?> Next we need to set up the urlManager component, so that the user data can be accessed and manipulated with meaningful HTTP verbs and pretty URLs. To let the API access data in JSON, we should configure the parsers property of the request application component. Step 2 − Modify the config/web.php file this way − <?php $params = require(__DIR__ . ”/params.php”); $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”components” => [ ”request” => [ // !!! insert a secret key in the following (if it is empty) – this is //required by cookie validation ”cookieValidationKey” => ”ymoaYrebZHa8gURuolioHGlK8fLXCKjO”, ], ”cache” => [ ”class” => ”yiicachingFileCache”, ], ”user” => [ ”identityClass” => ”appmodelsUser”, ”enableAutoLogin” => true, ], ”errorHandler” => [ ”errorAction” => ”site/error”, ], ”mailer” => [ ”class” => ”yiiswiftmailerMailer”, // send all mails to a file by default. You have to set // ”useFileTransport” to false and configure a transport // for the mailer to send real emails. ”useFileTransport” => true, ], ”log” => [ ”traceLevel” => YII_DEBUG ? 3 : 0, ”targets” => [ [ ”class” => ”yiilogFileTarget”, ”levels” => [”error”, ”warning”], ], ], ], ”urlManager” => [ ”enablePrettyUrl” => true, ”enableStrictParsing” => true, ”showScriptName” => false, ”rules” => [ [”class” => ”yiirestUrlRule”, ”controller” => ”user”], ], ], ”request” => [ ”parsers” => [ ”application/json” => ”yiiwebJsonParser”, ] ], ”db” => require(__DIR__ . ”/db.php”), ], ”modules” => [ ”hello” => [ ”class” => ”appmoduleshelloHello”, ], ], ”params” => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for ”dev” environment $config[”bootstrap”][] = ”debug”; $config[”modules”][”debug”] = [ ”class” => ”yiidebugModule”, ]; $config[”bootstrap”][] = ”gii”; $config[”modules”][”gii”] = [ ”class” => ”yiigiiModule”, ]; } return $config; ?> With the minimal amount of effort, we”ve just built a RESTful API for accessing user data. The APIs include − GET /users − list all users page by page HEAD /users − show the overview information of user listing POST /users − create a new user GET /users/20 − return the details of the user 20 HEAD /users/20 − show the overview information of user 20 PATCH /users/ 20 and PUT /users/20 − update the user 20 DELETE /users/20 − delete the user 20 OPTIONS /users − show the supported verbs regarding endpoint /users OPTIONS /users/20 − show the supported verbs regarding endpoint /users/ 20 Notice, that Yii automatically pluralizes controller name. Step 3 − Now, open Postman, punch in http://localhost:8080/users, and click “Send”. You will see the following. Step 4 − To create a new user, change the request type to POST, add two body parameters: name and email, and click “Send”. Step 5 − You can use the fields parameter to specify which fields should be included in the result. For example, the URL http://localhost:8080/users?fields=id, name will only return the id and name fields as shown in the following screenshot. Print Page Previous Next Advertisements ”;
Yii – Error Handling
Yii – Error Handling ”; Previous Next Yii includes a built-in error handler. The Yii error handler does the following − Converts all non-fatal PHP errors into catchable exceptions. Displays all errors and exceptions with a detailed call stack. Supports different error formats. Supports using a controller action to display errors. To disable the error handler, you should define the YII_ENABLE_ERROR_HANDLER constant to be false in the entry script. The error handler is registered as an application component. Step 1 − You can configure it in the following way. return [ ”components” => [ ”errorHandler” => [ ”maxSourceLines” => 10, ], ], ]; The above configuration sets the number of source code lines to be displayed to 10. The error handler converts all non-fatal PHP errors into catchable exceptions. Step 2 − Add a new function called actionShowError() to the SiteController. public function actionShowError() { try { 5/0; } catch (ErrorException $e) { Yii::warning(“Ooops…division by zero.”); } // execution continues… } Step 3 − Go to the URL http://localhost:8080/index.php?r=site/show-error. You will see a warning message. If you want to show the user that his request is invalid, you may throw the yiiwebNotFoundHttpException. Step 4 − Modify the actionShowError() function. public function actionShowError() { throw new NotFoundHttpException(“Something unexpected happened”); } Step 5 − Type the address http://localhost:8080/index.php?r=site/show-error in the address bar. You will see the following HTTP error. When the YII_DEBUG constant is true, the error handler will display errors with a detailed call stack. When the constant is false, only the error message will be displayed. By default, the error handler shows errors using these views − @yii/views/errorHandler/exception.php − the view file is used when errors should be displayed with call stack information. @yii/views/errorHandler/error.php − the view file is used when errors should be displayed without call stack information. You can use dedicated error actions to customize the error display. Step 6 − Modify the errorHandler application component in the config/web.php file. <?php $params = require(__DIR__ . ”/params.php”); $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”components” => [ ”request” => [ // !!! insert a secret key in the following (if it is empty) – this //is required by cookie validation ”cookieValidationKey” => ”ymoaYrebZHa8gURuolioHGlK8fLXCKjO”, ], ”cache” => [ ”class” => ”yiicachingFileCache”, ], ”user” => [ ”identityClass” => ”appmodelsUser”, ”enableAutoLogin” => true, ], ”errorHandler” => [ ”errorAction” => ”site/error”, ], //other components… ”db” => require(__DIR__ . ”/db.php”), ], ”modules” => [ ”hello” => [ ”class” => ”appmoduleshelloHello”, ], ], ”params” => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for ”dev” environment $config[”bootstrap”][] = ”debug”; $config[”modules”][”debug”] = [ ”class” => ”yiidebugModule”, ]; $config[”bootstrap”][] = ”gii”; $config[”modules”][”gii”] = [ ”class” => ”yiigiiModule”, ]; } return $config; ?> The above configuration defines that when an error needs to be displayed without the call stack, the site/error action will be executed. Step 7 − Modify the actions() method of the SiteController. public function actions() { return [ ”error” => [ ”class” => ”yiiwebErrorAction”, ], ]; } The above code defines, that when an error occurs, the error view will be rendered. Step 8 − Create a file called error.php under the views/site directory. <?php /* @var $this yiiwebView */ /* @var $name string */ /* @var $message string */ /* @var $exception Exception */ use yiihelpersHtml; $this->title = $name; ?> <div class = “site-error”> <h2>customized error</h2> <h1><?= Html::encode($this->title) ?></h1> <div class = “alert alert-danger”> <?= nl2br(Html::encode($message)) ?> </div> <p> The above error occurred while the Web server was processing your request. </p> <p> Please contact us if you think this is a server error. Thank you. </p> </div> Step 9 − Go to the address http://localhost:8080/index.php?r=site/show-error, you will see the customized error view. Print Page Previous Next Advertisements ”;
Yii – Localization
Yii – Localization ”; Previous Next I18N (Internationalization) is the process of designing an application that can be adapted to various languages. Yii offers a full spectrum of I18N features. Locale is a set of parameters that specify a user”s language and country. For example, the en-US stands for the English locale and the United States. Yii provides two types of languages: source language and target language. The source language is the language in which all text messages in the application are written. The target language is the language that should be used to display content to end users. The message translation component translates text messages from the source language to the target language. To translate the message, the message translation service must look it up in a message source. To use the message translation service, you should − Wrap text messages you want to be translated in the Yii::t() method. Configure message sources. Store messages in the message source. Step 1 − The Yii::t() method can be used like this. echo Yii::t(”app”, ”This is a message to translate!”); In the above code snippet, the ”app” stands for a message category. Step 2 − Now, modify the config/web.php file. <?php $params = require(__DIR__ . ”/params.php”); $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”components” => [ ”request” => [ // !!! insert a secret key in the following (if it is empty) – this //is required by cookie validation ”cookieValidationKey” => ”ymoaYrebZHa8gURuolioHGlK8fLXCKjO”, ], ”cache” => [ ”class” => ”yiicachingFileCache”, ], ”i18n” => [ ”translations” => [ ”app*” => [ ”class” => ”yiii18nPhpMessageSource”, ”fileMap” => [ ”app” => ”app.php” ], ], ], ], ”user” => [ ”identityClass” => ”appmodelsUser”, ”enableAutoLogin” => true, ], ”errorHandler” => [ ”errorAction” => ”site/error”, ], ”mailer” => [ ”class” => ”yiiswiftmailerMailer”, // send all mails to a file by default. You have to set // ”useFileTransport” to false and configure a transport // for the mailer to send real emails. ”useFileTransport” => true, ], ”log” => [ ”flushInterval” => 1, ”traceLevel” => YII_DEBUG ? 3 : 0, ”targets” => [ [ ”class” => ”yiilogFileTarget”, ”exportInterval” => 1, ”logVars” => [], ], ], ], ”db” => require(__DIR__ . ”/db.php”), ], // set target language to be Russian ”language” => ”ru-RU”, // set source language to be English ”sourceLanguage” => ”en-US”, ”modules” => [ ”hello” => [ ”class” => ”appmoduleshelloHello”, ], ], ”params” => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for ”dev” environment $config[”bootstrap”][] = ”debug”; $config[”modules”][”debug”] = [ ”class” => ”yiidebugModule”, ]; $config[”bootstrap”][] = ”gii”; $config[”modules”][”gii”] = [ ”class” => ”yiigiiModule”, ]; } return $config; ?> In the above code, we define the source and the target languages. We also specify a message source supported by yiii18nPhpMessageSource. The app* pattern indicates that all messages categories starting with app must be translated using this particular message source. In the above configuration, all Russian translations will be located in the messages/ru-RU/app.php file. Step 3 − Now, create the messages/ru-RU directory structure. Inside the ru-RU folder create a file called app.php. This will store all EN → RU translations. <?php return [ ”This is a string to translate!” => ”Эта строка для перевода!” ]; ?> Step 4 − Create a function called actionTranslation() in the SiteController. public function actionTranslation() { echo Yii::t(”app”, ”This is a string to translate!”); } Step 5 − Enter the URL http://localhost:8080/index.php?r=site/translation in the web browser, you will see the following. The message was translated into Russian as we set the target language to ru-RU. We can dynamically change the language of the application. Step 6 − Modify the actionTranslation() method. public function actionTranslation() { Yii::$app->language = ”en-US”; echo Yii::t(”app”, ”This is a string to translate!”); } Now, the message is displayed in English − Step 7 − In a translated message, you can insert one or multiple parameters. public function actionTranslation() { $username = ”Vladimir”; // display a translated message with username being “Vladimir” echo Yii::t(”app”, ”Hello, {username}!”, [ ”username” => $username, ]), “<br>”; $username = ”John”; // display a translated message with username being “John” echo Yii::t(”app”, ”Hello, {username}!”, [ ”username” => $username, ]), “<br>”; $price = 150; $count = 3; $subtotal = 450; echo Yii::t(”app”, ”Price: {0}, Count: {1}, Subtotal: {2}”, [$price, $count, $subtotal]); } Following will be the output. You can translate a whole view script, instead of translating individual text messages. For example, if the target language is ru-RU and you want to translate the views/site/index.php view file, you should translate the view and save it under the views/site/ru-RU directory. Step 8 − Create the views/site/ru-RU directory structure. Then, inside the ru-RU folder create a file called index.php with the following code. <?php /* @var $this yiiwebView */ $this->title = ”My Yii Application”; ?> <div class = “site-index”> <div class = “jumbotron”> <h1>Добро пожаловать!</h1> </div> </div> Step 9 − The target language is ru-RU, so if you enter the URL http://localhost:8080/index.php?r=site/index, you will see the page with Russian translation. Print Page Previous Next Advertisements ”;
Yii – Database Access
Yii – Database Access ”; Previous Next Yii DAO (Database Access Object) provides an API for accessing databases. It also serves as the foundation for other database access methods: active record and query builder. Yii DAO supports the following databases − MySQL MSSQL SQLite MariaDB PostgreSQL ORACLE CUBRID Creating a Database Connection Step 1 − To create a database connection, you need to create an instance of the yiidbConnection class. $mydb = new yiidbConnection([ ”dsn” => ”mysql:host=localhost;dbname=mydb”, ”username” => ”username”, ”password” => ”password”, ”charset” => ”utf8”, ]); A common practice is to configure a DB connection inside the application components. For example, in the basic application template the DB connection configuration is located in the config/db.php file as shown in the following code. <?php return [ ”class” => ”yiidbConnection”, ”dsn” => ”mysql:host = localhost;dbname = helloworld”, ”username” => ”vladimir”, ”password” => ”123574896”, ”charset” => ”utf8”, ]; ?> Step 2 − To access the DB connection you may use this expression. Yii::$app->db To configure a DB connection, you should specify its DSN (Data Source Name) via the dsn property. The DSN format varies for different databases − MySQL, MariaDB − mysql:host = localhost;dbname = mydb PostgreSQL − pgsql:host = localhost;port = 5432;dbname = mydb SQLite − sqlite:/path/to/db/file MS SQL Server (via sqlsrv driver) − sqlsrv:Server = localhost;Database = mydb MS SQL Server (via mssql driver) − mssql:host = localhost;dbname = mydb MS SQL Server (via dblib driver) − dblib:host = localhost;dbname = mydb CUBRID − cubrid:dbname = mydb;host = localhost;port = 33000 Oracle − oci:dbname = //localhost:1521/mydb To show database querying in action, we need data. Preparing the DB Step 1 − Create a new database. Database can be prepared in the following two ways. In the terminal run mysql -u root –p. Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci; Step 2 − Configure the database connection in the config/db.php file. The following configuration is for the system used currently. <?php return [ ”class” => ”yiidbConnection”, ”dsn” => ”mysql:host = localhost;dbname = helloworld”, ”username” => ”vladimir”, ”password” => ”12345”, ”charset” => ”utf8”, ]; ?> Step 3 − Inside the root folder run ./yii migrate/create test_table. This command will create a database migration for managing our DB. The migration file should appear in the migrations folder of the project root. Step 4 − Modify the migration file (m160106_163154_test_table.php in this case) this way. <?php use yiidbSchema; use yiidbMigration; class m160106_163154_test_table extends Migration { public function safeUp() { $this->createTable(“user”, [ “id” => Schema::TYPE_PK, “name” => Schema::TYPE_STRING, “email” => Schema::TYPE_STRING, ]); $this->batchInsert(“user”, [“name”, “email”], [ [“User1”, “[email protected]”], [“User2”, “[email protected]”], [“User3”, “[email protected]”], [“User4”, “[email protected]”], [“User5”, “[email protected]”], [“User6”, “[email protected]”], [“User7”, “[email protected]”], [“User8”, “[email protected]”], [“User9”, “[email protected]”], [“User10”, “[email protected]”], [“User11”, “[email protected]”], ]); } public function safeDown() { $this->dropTable(”user”); } } ?> The above migration creates a user table with these fields: id, name, and email. It also adds a few demo users. Step 5 − Inside the project root run ./yii migrate to apply the migration to the database. Step 6 − Now, we need to create a model for our user table. For the sake of simplicity, we are going to use the Gii code generation tool. Open up this url: http://localhost:8080/index.php?r=gii. Then, click the “Start” button under the “Model generator” header. Fill in the Table Name (“user”) and the Model Class (“MyUser”), click the “Preview” button and finally, click the “Generate” button. The MyUser model should appear in the models directory. Print Page Previous Next Advertisements ”;
Gii – Creating a Model
Gii – Creating a Model ”; Previous Next To create a Model in Gii − <?php namespace appmodels; use appcomponentsUppercaseBehavior; use Yii; /** * This is the model class for table “user”. * * @property integer $id * @property string $name * @property string $email */ class MyUser extends yiidbActiveRecord { /** * @inheritdoc */ public static function tableName() { return ”user”; } /** * @inheritdoc */ public function rules() { return [ [[”name”, ”email”], ”string”, ”max” => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ ”id” => ”ID”, ”name” => ”Name”, ”email” => ”Email”, ]; } } ?> Generating CRUD Let us generate CRUD for the MyUser model. Step 1 − Open the CRUD generator interface, fill in the form. Step 2 − Then, click the “Preview” button and “Generate”. Go to the URL http://localhost:8080/index.php?r=my-user, you will see the list of all users. Step 3 − Open the URL http://localhost:8080/index.php?r=my-user/create. You should see a user create form. Print Page Previous Next Advertisements ”;
Yii – Properties
Yii – Properties ”; Previous Next Class member variables in PHP are also called properties. They represent the state of class instance. Yii introduces a class called yiibaseObject. It supports defining properties via getter or setter class methods. A getter method starts with the word get. A setter method starts with set. You can use properties defined by getters and setters like class member variables. When a property is being read, the getter method will be called. When a property is being assigned, the setter method will be called. A property defined by a getter is read only if a setter is not defined. Step 1 − Create a file called Taxi.php inside the components folder. <?php namespace appcomponents; use yiibaseObject; class Taxi extends Object { private $_phone; public function getPhone() { return $this->_phone; } public function setPhone($value) { $this->_phone = trim($value); } } ?> In the code above, we define the Taxi class derived from the Object class. We set a getter – getPhone() and a setter – setPhone(). Step 2 − Now, add an actionProperties method to the SiteController. public function actionProperties() { $object = new Taxi(); // equivalent to $phone = $object->getPhone(); $phone = $object->phone; var_dump($phone); // equivalent to $object->setLabel(”abc”); $object->phone = ”79005448877”; var_dump($object); } In the above function we created a Taxi object, tried to access the phone property via the getter, and set the phone property via the setter. Step 3 − In your web browser, type http://localhost:8080/index.php?r=site/properties, in the address bar, you should see the following output. Print Page Previous Next Advertisements ”;