Yii – Layouts ”; Previous Next Layouts represent the common parts of multiple views i.e. for example, page header and footer. By default, layouts should be stored in the views/layouts folder. Let us have a look at the main layout of the basic application template − <?php /* @var $this yiiwebView */ /* @var $content string */ use yiihelpersHtml; use yiibootstrapNav; use yiibootstrapNavBar; use yiiwidgetsBreadcrumbs; use appassetsAppAsset; AppAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang = “<?= Yii::$app->language ?>”> <head> <meta charset = “<?= Yii::$app->charset ?>”> <meta name = “viewport” content = “width = device-width, initial-scale = 1”> <?= Html::csrfMetaTags() ?> <title><?= Html::encode($this->title) ?></title> <?php $this->head() ?> </head> <body> <?php $this->beginBody() ?> <div class = “wrap”> <?php NavBar::begin([ ”brandLabel” => ”My Company”, ”brandUrl” => Yii::$app->homeUrl, ”options” => [ ”class” => ”navbar-inverse navbar-fixed-top”, ], ]); echo Nav::widget([ ”options” => [”class” => ”navbar-nav navbar-right”], ”items” => [ [”label” => ”Home”, ”url” => [”/site/index”]], [”label” => ”About”, ”url” => [”/site/about”]], [”label” => ”Contact”, ”url” => [”/site/contact”]], Yii::$app->user->isGuest ? [”label” => ”Login”, ”url” => [”/site/login”]] : [ ”label” => ”Logout (” . Yii::$app->user->identity->username.”)”, ”url” => [”/site/logout”], ”linkOptions” => [”data-method” => ”post”] ], ], ]); NavBar::end(); ?> <div class = “container”> <?= Breadcrumbs::widget([ ”links” => isset($this->params[”breadcrumbs”]) ? $this>params [”breadcrumbs”] : [], ]) ?> <?= $content ?> </div> </div> <footer class = “footer”> <div class = “container”> <p class = “pull-left”>© My Company <?= date(”Y”) ?></p> <p class = “pull-right”><?= Yii::powered() ?></p> </div> </footer> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?> This layout generates the HTML page that is common for all pages. The $content variable is the rendering result of content views. The following methods trigger events about the rendering process so that the scripts and tags registered in other places could be properly injected − head() − Should be called within the head section. Generates a placeholder, which will be replaced with the registered HTML targeted at the head position. beginBody() − Should be called at the beginning of the body section. Triggers the EVENT_BEGIN_BODY event. Generates a placeholder which will be replaced with the registered HTML targeted at the body begin position. endBody() − Should be called at the end of the body section. Triggers the EVENT_END_BODY event. Generates a placeholder, which will be replaced with the registered HTML targeted at the body end position. beginPage() − Should be called at the beginning of the layout. Triggers the EVENT_BEGIN_PAGE event. endPage() − Should be called at the end of the layout. Triggers the EVENT_END_PAGE event. Create a Layout Step 1 − Inside the views/layouts directory, create a file called newlayout.php with the following code. <?php /* @var $this yiiwebView */ /* @var $content string */ use yiihelpersHtml; use yiibootstrapNav; use yiibootstrapNavBar; use yiiwidgetsBreadcrumbs; use appassetsAppAsset; AppAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang = “<?= Yii::$app->language ?>”> <head> <meta charset = “<?= Yii::$app->charset ?>”> <meta name = “viewport” content = “width = device-width, initial-scale = 1”> <? = Html::csrfMetaTags() ?> <title><? = Html::encode($this->title) ?></title> <?php $this->head() ?> </head> <body> <?php $this->beginBody() ?> <div class = “wrap”> <div class = “container”> <? = $content ?> </div> </div> <footer class = “footer”> <div class = “container”> <p class = “pull-left”>© My Company <?= date(”Y”) ?></p> <p class = “pull-right”><? = Yii::powered() ?></p> </div> </footer> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?> We have removed the top menu bar. Step 2 − To apply this layout to the SiteController, add the $layout property to the SiteController class. <?php namespace appcontrollers; use Yii; use yiifiltersAccessControl; use yiiwebController; use yiifiltersVerbFilter; use appmodelsLoginForm; use appmodelsContactForm; class SiteController extends Controller { public $layout = “newlayout”; /* other methods */ } ?> Step 3 − Now if you go to the web browser at any view of the SiteController, you will see that the layout has changed. Step 4 − To register various meta tags, you can call yiiwebView::registerMetaTag() in a content view. Step 5 − Modify the ‘About’ view of the SiteController. <?php /* @var $this yiiwebView */ use yiihelpersHtml; $this->title = ”About”; $this->params[”breadcrumbs”][] = $this->title; $this->registerMetaTag([”name” => ”keywords”, ”content” => ”yii, developing, views, meta, tags”]); $this->registerMetaTag([”name” => ”description”, ”content” => ”This is the description of this page!”], ”description”); ?> <div class=”site-about”> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <code><?= __FILE__ ?></code> </div> We have just registered two meta tags − keywords and description. Step 6 − Now go to http://localhost:8080/index.php?r=site/about, you will find the meta tags in the head section of the page as shown in the following screenshot. Views trigger several events − EVENT_BEGIN_BODY − triggered in layouts by the call of yiiwebView::beginBody(). EVENT_END_BODY − triggered in layouts by the call of yiiwebView::endBody(). EVENT_BEGIN_PAGE − triggered in layouts by the call of yiiwebView::beginPage(). EVENT_END_PAGE − triggered in layouts by the call of yiiwebView::endPage(). EVENT_BEFORE_RENDER − triggered in a controller at the beginning of rendering a file. EVENT_AFTER_RENDER − triggered after rendering a file. You may respond to these events to inject content into views. Step 7 − To display the current date and time in the actionAbout of the SiteController, modify it this way. public function actionAbout() { Yii::$app->view->on(View::EVENT_BEGIN_BODY, function () { echo date(”m.d.Y H:i:s”); }); return $this->render(”about”); } Step 8 − Type http://localhost:8080/index.php?r=site/about in the address bar of the web browser and you will see the following. Important Points To make Views more manageable you should − Divide complex views into several smaller ones. Use layouts for common HTML sections (headers, footers, menus and so forth). Use widgets. Views should − Contain HTML and simple PHP code to format and render data. NOT process requests. NOT modify model properties. NOT perform database queries. Print Page Previous Next Advertisements ”;
Category: yii
Yii – Useful Resources
Yii – Useful Resources ”; Previous Next The following resources contain additional information on Yii. Please use them to get more in-depth knowledge on this. Useful Links on Yii Yii Wikipedia – Wikipedia Reference for Yii. Yii Official Site – Official Site for Yii. Useful Books on Yii To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Yii – Discussion
Discuss Yii ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Yii – Caching
Yii – Caching ”; Previous Next Caching is an effective way to improve the performance of your application. Caching mechanisms store static data in cache and get it from cache when requested. On the server side, you may use cache to store basic data, such as a list of most recent news. You can also store page fragments or whole web pages. On the client side, you can use HTTP caching to keep most recently visited pages in the browser cache. 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. Data Caching Data caching helps you in storing PHP variables in cache and retrieve them later. Data caching relies on cache components, which are usually registered as application components. To access the application component, you may call Yii::$app → cache. You can register several cache application components. Yii supports the following cache storages − yiicachingDbCache − Uses a database table to store cached data. Uou must create a table as specified in yiicachingDbCache::$cacheTable. yiicachingApcCache − Uses PHP APC extension. yiicachingFileCache − Uses files to store cached data. yiicachingDummyCache − Serves as a cache placeholder which does no real caching. The purpose of this component is to simplify the code that needs to check the availability of cache. yiicachingMemCache − Uses PHP memcache extension. yiicachingWinCache − Uses PHP WinCache extension. yiiredisCache − Implements a cache component based on Redis database. yiicachingXCache − Uses PHP XCache extension. All cache components support the following APIs − get() − Retrieves a data value from cache with a specified key. A false value will be returned if the data value is expired/invalidated or not found. add() − Stores a data value identified by a key in cache if the key is not found in the cache. set() − Stores a data value identified by a key in cache. multiGet() − Retrieves multiple data values from cache with the specified keys. multiAdd() − Stores multiple data values in cache. Each item is identified by a key. If a key already exists in the cache, the data value will be skipped. multiSet() − Stores multiple data values in cache. Each item is identified by a key. exists() − Returns a value indicating whether the specified key is found in the cache. flush() − Removes all data values from the cache. delete() − Removes a data value identified by a key from the cache. A data value stored in a cache will remain there forever unless it is removed. To change this behavior, you can set an expiration parameter when calling the set() method to store a data value. Cached data values can also be invalidated by changes of the cache dependencies − yiicachingDbDependency − The dependency is changed if the query result of the specified SQL statement is changed. yiicachingChainedDependency − The dependency is changed if any of the dependencies on the chain is changed. yiicachingFileDependency − The dependency is changed if the file”s last modification time is changed. yiicachingExpressionDependency − The dependency is changed if the result of the specified PHP expression is changed. Now, add the cache application component to your application. Step 1 − 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”, ], ”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”], ], ], ], ”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”;
Yii – Quick Guide
Yii – Quick Guide ”; Previous Next Yii – Overview 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. 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. It also has a code generation tool called Gii that includes the full CRUD(Create-Read-Update-Delete) interface maker. Core Features The core features of Yii are as follows − Yii implements the MVC architectural pattern. It provides features for both relational and NoSQL databases. Yii never over-designs things for the sole purpose of following some design pattern. It is extremely extensible. Yii provides multi-tier caching support. Yii provides RESTful API development support. It has high performance. Overall, if all you need is a neat interface for the underlying database, then Yii is the right choice. Currently, Yii has two versions: 1.1 and 2.0. Version 1.1 is now in maintenance mode and Version 2 adopts the latest technologies, including Composer utility for package distribution, PSR levels 1, 2, and 4, and many PHP 5.4+ features. It is version 2 that will receive the main development effort over the next few years. 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. It would be easier for you to pick up Yii 2.0 if you understand these concepts. Environment The major requirements for Yii2 are PHP 5.4+ and a web server. Yii is a powerful console tool, which manages database migrations, asset compilation, and other stuff. It is recommended to have a command line access to the machine where you develop your application. For development purpose, we will use − Linux Mint 17.1 PHP 5.5.9 PHP built-in web server Pre-installation check To check whether your local machine is good to go with the latest Yii2 version, do the following − Step 1 − Install the latest php version. sudo apt-get install php5 Step 2 − Install the latest mysql version. sudo apt-get install mysql-server Step 3 − Download the Yii2 basic application template. composer create-project –prefer-dist –stability=dev yiisoft/yii2-app-basic basic Step 4 − To start a PHP built-in server, inside the basic folder run. php -S localhost:8080 There is a useful script, requirements.php. It checks whether your server meets the requirements to run the application. You can find this script in the root folder of your application. If you type http://localhost:8080/requirements.php in the address bar of the web browser, the page looks like as shown in the following screenshot − Yii – Installation The most straightforward way to get started with Yii2 is to use the basic application template provided by the Yii2 team. This template is also available through the Composer tool. Step 1 − Find a suitable directory in your hard drive and download the Composer PHAR (PHP archive) via the following command. curl -sS https://getcomposer.org/installer | php Step 2 − Then move this archive to the bin directory. mv composer.phar /usr/local/bin/composer Step 3 − With the Composer installed, you can install Yii2 basic application template. Run these commands. composer global require “fxp/composer-asset-plugin:~1.1.1” composer create-project –prefer-dist yiisoft/yii2-app-basic helloworld The first command installs the composer asset plugin, which manages npm and bower dependencies. The second command installs Yii2 basic application template in a directory called helloworld. Step 4 − Now open the helloworld directory and launch the web server built into PHP. php -S localhost:8080 -t web Step 5 − Then open http://localhost:8080 in your browser. You can see the welcome page. Yii – Create Page Now we are going to create a “Hello world” page in your application. To create a page, we must create an action and a view. Actions are declared in controllers. The end user will receive the execution result of an action. Step 1 − Declare the speak action in the existing SiteController, which is defined in the class file controllers/SiteController.php. <?php namespace appcontrollers; use Yii; use yiifiltersAccessControl; use yiiwebController; use yiifiltersVerbFilter; use appmodelsLoginForm; use appmodelsContactForm; class SiteController extends Controller { /* other code */ public function actionSpeak($message = “default message”) { return $this->render(“speak”,[”message” => $message]); } } ?> We defined the speak action as a method called actionSpeak. In Yii, all action methods are prefixed with the word action. This is how the framework differentiates action methods from non-action ones. If an action ID requires multiple words, then they will be concatenated by dashes. Hence, the action ID add-post corresponds to the action method actionAddPost. In the code given above, the ‘out’ function takes a GET parameter, $message. We also call a method named ‘render’ to render a view file called speak. We pass the message parameter to the view. The rendering result is a complete HTML page. View is a script that generates a response”s content. For the speak action, we create a speak view that prints our message. When the render method is called, it looks for a PHP file names as view/controllerID/vewName.php. Step 2 − Therefore, inside the views/site folder create a file called speak.php with the following code. <?php use yiihelpersHtml; ?> <?php echo Html::encode($message); ?> Note that we HTML-encode the message parameter before printing to avoid XSS attack. Step 3 − Type the following in your web browser http://localhost:8080/index.php?r=site/speak&message=hello%20world. You will see the following window − The ‘r’ parameter in the URL stands for route. The route”s default format is controllerID/actionID. In our case, the route site/speak will be resolved by the SiteController class and the speak action. Yii – Application Structure There is only one folder in the overall code base that is publicly available for the web server. It is the web directory. Other folders outside the web root directory are out of reach for the web server. Note
Yii – RESTful APIs
Yii – RESTful APIs ”; Previous Next Yii provides the following useful features for implementing RESTful APIs − Quick prototyping Customizable object serialization Response format (supporting JSON and XML by default) Formatting of collection data and validation errors Efficient routing Support for HATEOAS Built-in support for the OPTIONS and HEAD verbs Data caching and HTTP caching Authentication and authorization Rate limiting To show RESTful APIs 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. Installing Postman Postman is a handy tool when developing a RESTful service. It provides a useful interface for constructing requests. You can find this tool at https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en . To install it, press the “Add to Chrome” button. Print Page Previous Next Advertisements ”;
Yii – Behaviors
Yii – Behaviors ”; Previous Next Behaviors are instances of the yiibaseBehavior class. A behavior injects its methods and properties to the component it is attached to. Behaviors can also respond to the events triggered by the component. Step 1 − To define a behavior, extend the yiibaseBehavior class. namespace appcomponents; use yiibaseBehavior; class MyBehavior extends Behavior { private $_prop1; public function getProp1() { return $this->_prop1; } public function setProp1($value) { $this->_prop1 = $value; } public function myFunction() { // … } } The above code defines the behavior with one property (prop1) and one method (myFunction). When this behavior is attached to a component, that component will also have the prop1 property and the myFunction method. To access the component the behavior is attached to, you may use the yiibaseBehavior::$owner property. Step 2 − If you want a behavior to respond to the component events, you should override the yiibaseBehavior::events() method. namespace appcomponents; use yiidbActiveRecord; use yiibaseBehavior; class MyBehavior extends Behavior { public function events() { return [ ActiveRecord::EVENT_AFTER_VALIDATE => ”afterValidate”, ]; } public function afterValidate($event) { // … } } Step 3 − To attach a behavior, you should override the behaviors() method of the component class. namespace appmodels; use yiidbActiveRecord; use appcomponentsMyBehavior; class MyUser extends ActiveRecord { public function behaviors() { return [ // anonymous behavior, behavior class name only MyBehavior::className(), // named behavior, behavior class name only ”myBehavior2” => MyBehavior::className(), // anonymous behavior, configuration array [ ”class” => MyBehavior::className(), ”prop1” => ”value1”, ”prop2” => ”value2”, ”prop3” => ”value3”, ], // named behavior, configuration array ”myBehavior4” => [ ”class” => MyBehavior::className(), ”prop1” => ”value1” ] ]; } } Step 4 − To detach a behavior, call the yiibaseComponent::detachBehavior() method. $component->detachBehavior(”myBehavior”); To show behaviors 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 ”;
Yii – Fields
Yii – Fields ”; Previous Next By overriding fields() and extraFields() methods, you can define what data can be put into a response. The difference between these two methods is that the former defines the default set of fields, which should be included in the response while the latter defines additional fields, which may be included in the response if an end user requests for them via the expand query parameter. Step 1 − Modify the MyUser model this way. <?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 { public function fields() { return [ ”id”, ”name”, //PHP callback ”datetime” => function($model) { return date(“d:m:Y H:i:s”); } ]; } /** * @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”, ]; } } ?> Besides default fields: id and name, we have added a custom field – datetime. Step 2 − In Postman, run the URL http://localhost:8080/users. Step 3 − Now, modify the MyUser model this way. <?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 { public function fields() { return [ ”id”, ”name”, ]; } public function extraFields() { return [”email”]; } /** * @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”, ]; } } ?> Notice, that the email field is returned by the extraFields() method. Step 4 − To get data with this field, run http://localhost:8080/users?expand=email. Customizing Actions The yiirestActiveController class provides the following actions − Index − Lists resources page by page View − Returns the details of a specified resource Create − Creates a new resource Update − Updates an existing resource Delete − Deletes the specified resource Options − Returns the supported HTTP methods All above actions are declared in the actions method(). To disable the “delete” and “create” actions, modify the UserController this way − <?php namespace appcontrollers; use yiirestActiveController; class UserController extends ActiveController { public $modelClass = ”appmodelsMyUser”; public function actions() { $actions = parent::actions(); // disable the “delete” and “create” actions unset($actions[”delete”], $actions[”create”]); return $actions; } } ?> Handling Errors When obtaining a RESTful API request, if there is an error in the request or something unexpected happens on the server, you may simply throw an exception. If you can identify the cause of the error, you should throw an exception along with a proper HTTP status code. Yii REST uses the following statuses − 200 − OK. 201 − A resource was successfully created in response to a POST request. The Location header contains the URL pointing to the newly created resource. 204 − The request was handled successfully and the response contains no content. 304 − The resource was not modified. 400 − Bad request. 401 − Authentication failed. 403 − The authenticated user is not allowed to access the specified API endpoint. 404 − The resource does not exist. 405 − Method not allowed. 415 − Unsupported media type. 422 − Data validation failed. 429 − Too many requests. 500 − Internal server error. Print Page Previous Next Advertisements ”;
Yii – Testing
Yii – Testing ”; Previous Next When we write a PHP class, we debug it step by step or use die or echo statements to verify how it works. If we develop a web application, we are entering test data in forms to ensure the page works as we expected. This test process can be automated. Automatic test approach makes sense for long term projects, which are − Complex and large Grows constantly Too expensive in terms of cost of the failure If your project is not getting complex and is relatively simple or it is just a one-time project, then automated testing can be an overkill. Preparing for the Tests Step 1 − Install the Codeception framework. Run the following code. composer global require “codeception/codeception = 2.0.*” composer global require “codeception/specify = *” composer global require “codeception/verify = *” Step 2 − Run the following. composer global status The output is “Changed current directory to <directory>”. You should add the ”<directory>/vendor/bin” to your PATH variable. In this case, run the following code − export PATH = $PATH:~/.composer/vendor/bin Step 3 − Create a new database called ”yii2_basic_tests”. Step 4 − Inside the tests directory run. codeception/bin/yii migrate The database configuration can be found at tests/codeception/config/config.php. Step 5 − Build the test suites via. codecept build Fixtures The main purpose of fixtures is to set up the environment in an unknown state so that your tests run in an expected way. Yii provides a near fixture framework. A key concept of the Yii fixture framework is the fixture object. It represents a particular aspect of a test environment. The fixture object is an instance of the yiitestFixture class. To define a fixture, you should create a new class and extend it from yiitestFixture or yiitestActiveFixture. The former is better for general purpose fixtures while the latter is specifically designed to work with database and ActiveRecord. Unit Tests Unit tests help you testing individual functions. For example, model functions or a component class. Step 1 − Create a new fixture in the file called ExampleFixture.php under the tests/codeception/fixtures directory. <?php namespace apptestscodeceptionfixtures; use yiitestActiveFixture; class ExampleFixture extends ActiveFixture { public $modelClass = ‘app⊨’MyUser”; } ?> Step 2 − Then, create a new test file called ExampleTest.php in the tests/codeception/unit/models folder. <?php namespace testscodeceptionunitmodels; use appmodelsMyUser; use yiicodeceptionTestCase; class ExampleTest extends TestCase { public function testCreateMyUser() { $m = new MyUser(); $m->name = “myuser”; $m->email = “[email protected]”; $this->assertTrue($m->save()); } public function testUpdateMyUser() { $m = new MyUser(); $m->name = “myuser2”; $m->email = “[email protected]”; $this->assertTrue($m->save()); $this->assertEquals(“myuser2″, $m->name); } public function testDeleteMyUser() { $m = MyUser::findOne([”name” => ”myuser2”]); $this->assertNotNull($m); MyUser::deleteAll([”name” => $m->name]); $m = MyUser::findOne([”name” => ”myuser2”]); $this->assertNull($m); } } ?> In the above code, we define three tests − testCreateMyUser, testUpdateMyUser, and testDeleteMyUser. We just created a new user, updated his name, and trying to delete him. We manage the MyUser model in terms of the yii2_basic_tests database, which is a complete copy of our real DB. Step 3 − To start the tests, move to the tests folder and run. codecept run unit models/ExampleTest It should pass all the tests. You will see the following − Functional Tests Functional tests help you in − testing the application using browser emulator verify that the function works properly interact with the database submit data to server-side scripts Inside the tests folder run − generate:cept functional AboutPageCept The above command creates the AboutPageCept.php file under the tests/codeception/functional folder. In this functional test, we are going to check whether our about page exists. Step 1 − Modify the AboutPageCept.php file. <?php $I = new FunctionalTester($scenario); $I->wantTo(”perform actions and see result”); $I->amOnPage(”site/about”); $I->see(”about”); $I->dontSee(”apple”); ?> In the above given code, we checked whether we are on the about page. Obviously, we should see the word ”about” and no ”apple” on the page. Step 2 − Run the test via. run functional AboutPageCept You will see the following output − Print Page Previous Next Advertisements ”;
Yii – Data Providers
Yii – Data Providers ”; Previous Next Yii provides a set of data provider classes that encapsulate pagination and sorting. A data provider implements yiidataDataProviderInterface. It supports retrieving sorted and paginated data. Data providers usually work with data widgets. Yii includes − ActiveDataProvider − Uses yiidbActiveQuery or yiidbQuery to query data from databases. SqlDataProvider − Executes SQL and returns data as arrays. ArrayDataProvider − Takes a big array and returns a slice of it. You define the sorting and pagination behaviors of a data-provider by configuring its pagination and sort properties. Data widgets, such as yiigridGridView, have a property called dataProvider, which takes a data provider instance and displays the data on the screen. 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. Active Data Provider Step 1 − Create a function called actionDataProvider inside the SiteController. public function actionDataProvider(){ $query = MyUser::find(); $provider = new ActiveDataProvider([ ”query” => $query, ”pagination” => [ ”pageSize” => 2, ], ]); // returns an array of users objects $users = $provider->getModels(); var_dump($users); } In the code above, we define an instance of the ActiveDataProvider class and display users from the first page. The yiidataActiveDataProvider class uses the DB application component as the DB connection. Step 2 − If you enter the local host address http://localhost:8080/index.php?r=site/dataprovider, you will see the following output. SQL Data Provider The yiidataSqlDataProvider class works with raw SQL statements. Step 1 − Modify the actionDataProvider method this way. public function actionDataProvider() { $count = Yii::$app->db->createCommand(”SELECT COUNT(*) FROM user”)->queryScalar(); $provider = new SqlDataProvider([ ”sql” => ”SELECT * FROM user”, ”totalCount” => $count, ”pagination” => [ ”pageSize” => 5, ], ”sort” => [ ”attributes” => [ ”id”, ”name”, ”email”, ], ], ]); // returns an array of data rows $users = $provider->getModels(); var_dump($users); } Step 2 − Type http://localhost:8080/index.php?r=site/data-provider in the address bar of the web browser, you will see the following output. Array Data Provider The yiidataArrayDataProvider class is best for working with big arrays. Elements in this array can be either query results of DAO or Active Record instances. Step 1 − Modify the actionDataProvider method this way. public function actionDataProvider() { $data = MyUser::find()->asArray()->all(); $provider = new ArrayDataProvider([ ”allModels” => $data, ”pagination” => [ ”pageSize” => 3, ], ”sort” => [ ”attributes” => [”id”, ”name”], ], ]); // get the rows in the currently requested page $users = $provider->getModels(); var_dump($users); } Step 2 − If you go to the address http://localhost:8080/index.php?r=site/data-provider through the web browser, you will see the following output. Notice, that unlike SQL Data Provider and Active Data Provider, Array Data Provider loads all data into the memory, so it is less efficient. Print Page Previous Next Advertisements ”;