Yii – Authentication ”; Previous Next The process of verifying the identity of a user is called authentication. It usually uses a username and a password to judge whether the user is one who he claims as. To use the Yii authentication framework, you need to − Configure the user application component. Implement the yiiwebIdentityInterface interface. The basic application template comes with a built-in authentication system. It uses the user application component as shown in the following code − <?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, ], //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; ?> In the above configuration, the identity class for user is configured to be appmodelsUser. The identity class must implement the yiiwebIdentityInterface with the following methods − findIdentity() − Looks for an instance of the identity class using the specified user ID. findIdentityByAccessToken() − Looks for an instance of the identity class using the specified access token. getId() − It returns the ID of the user. getAuthKey() − Returns a key used to verify cookie-based login. validateAuthKey() − Implements the logic for verifying the cookie-based login key. The User model from the basic application template implements all the above functions. User data is stored in the $users property − <?php namespace appmodels; class User extends yiibaseObject implements yiiwebIdentityInterface { public $id; public $username; public $password; public $authKey; public $accessToken; private static $users = [ ”100” => [ ”id” => ”100”, ”username” => ”admin”, ”password” => ”admin”, ”authKey” => ”test100key”, ”accessToken” => ”100-token”, ], ”101” => [ ”id” => ”101”, ”username” => ”demo”, ”password” => ”demo”, ”authKey” => ”test101key”, ”accessToken” => ”101-token”, ], ]; /** * @inheritdoc */ public static function findIdentity($id) { return isset(self::$users[$id]) ? new static(self::$users[$id]) : null; } /** * @inheritdoc */ public static function findIdentityByAccessToken($token, $type = null) { foreach (self::$users as $user) { if ($user[”accessToken”] === $token) { return new static($user); } } return null; } /** * Finds user by username * * @param string $username * @return static|null */ public static function findByUsername($username) { foreach (self::$users as $user) { if (strcasecmp($user[”username”], $username) === 0) { return new static($user); } } return null; } /** * @inheritdoc */ public function getId() { return $this->id; } /** * @inheritdoc */ public function getAuthKey() { return $this->authKey; } /** * @inheritdoc */ public function validateAuthKey($authKey) { return $this->authKey === $authKey; } /** * Validates password * * @param string $password password to validate * @return boolean if password provided is valid for current user */ public function validatePassword($password) { return $this->password === $password; } } ?> Step 1 − Go to the URL http://localhost:8080/index.php?r=site/login and log in into the web site using admin for a login and a password. Step 2 − Then, add a new function called actionAuth() to the SiteController. public function actionAuth(){ // the current user identity. Null if the user is not authenticated. $identity = Yii::$app->user->identity; var_dump($identity); // the ID of the current user. Null if the user not authenticated. $id = Yii::$app->user->id; var_dump($id); // whether the current user is a guest (not authenticated) $isGuest = Yii::$app->user->isGuest; var_dump($isGuest); } Step 3 − Type the address http://localhost:8080/index.php?r=site/auth in the web browser, you will see the detailed information about admin user. Step 4 − To login and logou,t a user you can use the following code. public function actionAuth() { // whether the current user is a guest (not authenticated) var_dump(Yii::$app->user->isGuest); // find a user identity with the specified username. // note that you may want to check the password if needed $identity = User::findByUsername(“admin”); // logs in the user Yii::$app->user->login($identity); // whether the current user is a guest (not authenticated) var_dump(Yii::$app->user->isGuest); Yii::$app->user->logout(); // whether the current user is a guest (not authenticated) var_dump(Yii::$app->user->isGuest); } At first, we check whether a user is logged in. If the value returns false, then we log in a user via the Yii::$app → user → login() call, and log him out using the Yii::$app → user → logout() method. Step 5 − Go to the URL http://localhost:8080/index.php?r=site/auth, you will see the following. The yiiwebUser class raises the following events − EVENT_BEFORE_LOGIN − Raised at the beginning of yiiwebUser::login() EVENT_AFTER_LOGIN − Raised after a successful login EVENT_BEFORE_LOGOUT − Raised at the beginning of yiiwebUser::logout() EVENT_AFTER_LOGOUT − Raised after a successful logout Print Page Previous Next Advertisements ”;
Category: yii
Yii – Authorization
Yii – Authorization ”; Previous Next The process of verifying that a user has enough permission to do something is called authorization. Yii provides an ACF (Access Control Filter), an authorization method implemented as yiifiltersAccessControl. Modify the behaviors() function of the SiteController − public function behaviors() { return [ ”access” => [ ”class” => AccessControl::className(), ”only” => [”about”, ”contact”], ”rules” => [ [ ”allow” => true, ”actions” => [”about”], ”roles” => [”?”], ], [ ”allow” => true, ”actions” => [”contact”, ”about”], ”roles” => [”@”], ], ], ], ]; } In the above code, ACF is attached as a behavior. The only property specifies that the ACF should be applied only to the about and contact actions. All other actions are not subjected to the access control. The rules property lists the access rules. All guests (with the “?” role) will be allowed to access the about action. All authenticated users(with the “@” role) will be allowed to access the contact and about actions. If you go to the URL http://localhost:8080/index.php?r=site/about, you will see the page, but if you open the URL http://localhost:8080/index.php?r=site/contact, you will be redirected to the login page because only authenticated users can access the contact action. Access rules support many options − allow − Defines whether this is an “allow” or “deny” rule. actions − Defines which actions this rule matches. controllers − Defines which controllers this rule matches. roles − Defines user roles that this rule matches. Two special roles are recognized − ? − matches a guest user. @ − matches an authenticated user. ips − Defines IP addresses this rule matches. verbs − Defines which request method (POST, GET, PUT, etc.) this rule matches. matchCallback − Defines a PHP callable function that should be called to check if this rule should be applied. denyCallback − Defines a PHP callable function that should be called when this rule will deny the access. Passwords Step 1 − Yii provides the following handy methods for working with passwords. public function actionAuth() { $password = “asd%#G3”; //generates password hasg $hash = Yii::$app->getSecurity()->generatePasswordHash($password); var_dump($hash); //validates password hash if (Yii::$app->getSecurity()->validatePassword($password, $hash)) { echo “correct password”; } else { echo “incorrect password”; } //generate a token $key = Yii::$app->getSecurity()->generateRandomString(); var_dump($key); //encrypt data with a secret key $encryptedData = Yii::$app->getSecurity()->encryptByPassword(“mydata”, $key); var_dump($encryptedData); //decrypt data with a secret key $data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $key); var_dump($data); //hash data with a secret key $data = Yii::$app->getSecurity()->hashData(“mygenuinedata”, $key); var_dump($data); //validate data with a secret key $data = Yii::$app->getSecurity()->validateData($data, $key); var_dump($data); } Step 2 − Enter the URL http://localhost:8080/index.php?r=site/auth, you will see the following. Print Page Previous Next Advertisements ”;
Yii – Logging
Yii – Logging ”; Previous Next Yii provides a highly customizable and extensible framework. With the help of this framework, you can easily log various types of messages. To log a message, you should call one of the following methods − Yii::error() − Records a fatal error message. Yii::warning() − Records a warning message. Yii::info() − Records a message with some useful information. Yii::trace() − Records a message to trace how a piece of code runs. The above methods record log messages at various categories. They share the following function signature − function ($message, $category = ”application”) where − $message − The log message to be recorded $category − The category of the log message A simple and convenient way of naming scheme is using the PHP __METHOD__ magic constant. For example − Yii::info(”this is a log message”, __METHOD__); A log target is an instance of the yiilogTarget class. It filters all log messages by categories and exports them to file, database, and/or email. Step 1 − You can register multiple log target as well, like. return [ // the “log” component is loaded during bootstrapping time ”bootstrap” => [”log”], ”components” => [ ”log” => [ ”targets” => [ [ ”class” => ”yiilogDbTarget”, ”levels” => [”error”, ”warning”, ”trace”, ”info”], ], [ ”class” => ”yiilogEmailTarget”, ”levels” => [”error”, ”warning”], ”categories” => [”yiidb*”], ”message” => [ ”from” => [”[email protected]”], ”to” => [”[email protected]”, ”[email protected]”], ”subject” => ”Application errors at mydomain.com”, ], ], ], ], ], ]; In the code above, two targets are registered. The first target selects all errors, warnings, traces, and info messages and saves them in a database. The second target sends all error and warning messages to the admin email. Yii provides the following built-in log targets − yiilogDbTarget − Stores log messages in a database. yiilogFileTarget − Saves log messages in files. yiilogEmailTarget − Sends log messages to predefined email addresses. yiilogSyslogTarget − Saves log messages to syslog by calling the PHP function syslog(). By default, log messages are formatted as follows − Timestamp [IP address][User ID][Session ID][Severity Level][Category] Message Text Step 2 − To customize this format, you should configure the yiilogTarget::$prefix property. For example. [ ”class” => ”yiilogFileTarget”, ”prefix” => function ($message) { $user = Yii::$app->has(”user”, true) ? Yii::$app->get(”user”) : ”undefined user”; $userID = $user ? $user->getId(false) : ”anonym”; return “[$userID]”; } ] The above code snippet configures a log target to prefix all log messages with the current userID. By default, log messages include the values from these global PHP variables: $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, and $_SERVER. To modify this behavior, you should configure the yiilogTarget::$logVars property with the names of variables that you want to include. All log messages are maintained in an array by the logger object. The logger object flushed the recorded messages to the log targets each time the array accumulates a certain number of messages(default is 1000). Step 3 − To customize this number, you should call the flushInterval property. return [ ”bootstrap” => [”log”], ”components” => [ ”log” => [ ”flushInterval” => 50, // default is 1000 ”targets” => […], ], ], ]; Even when the logger object flushes log messages to log targets, they do not get exported immediately. The export occurs when a log target accumulates a certain number of messages(default is 1000). Step 4 − To customize this number, you should configure the exportInterval property. [ ”class” => ”yiilogFileTarget”, ”exportInterval” => 50, // default is 1000 ] Step 5 − Now, 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” => [ ”flushInterval” => 1, ”traceLevel” => YII_DEBUG ? 3 : 0, ”targets” => [ [ ”class” => ”yiilogFileTarget”, ”exportInterval” => 1, ”logVars” => [] ], ], ], ”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; ?> In the above code, we define the log application component, set the flushInterval and exportInteval properties to 1 so that all log messages appear in the log files immediately. We also omit the levels property of the log target. It means that log messages of all categories(error, warning, info, trace) will appear in the log files. Step 6 − Then, create a function called actionLog() in the SiteController. public function actionLog() { Yii::trace(”trace log message”); Yii::info(”info log message”); Yii::warning(”warning log message”); Yii::error(”error log message”); } In the above code, we just write four log messages of different categories to the log files. Step 7 − Type the URL http://localhost:8080/index.php?r=site/log in the address bar of the web browser. Log messages should appear under the app/runtime/logs directory in the app.log file. Print Page Previous Next Advertisements ”;
Yii – Creating a Behavior
Yii – Creating a Behavior ”; Previous Next Assume we want to create a behavior that will uppercase the “name” property of the component the behavior is attached to. Step 1 − Inside the components folder, create a file called UppercaseBehavior.php with the following code. <?php namespace appcomponents; use yiibaseBehavior; use yiidbActiveRecord; class UppercaseBehavior extends Behavior { public function events() { return [ ActiveRecord::EVENT_BEFORE_VALIDATE => ”beforeValidate”, ]; } public function beforeValidate($event) { $this->owner->name = strtoupper($this->owner->name); } } ?> In the above code we create the UppercaseBehavior, which uppercase the name property when the “beforeValidate” event is triggered. Step 2 − To attach this behavior to the MyUser model, modify it 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 behaviors() { return [ // anonymous behavior, behavior class name only UppercaseBehavior::className(), ]; } /** * @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”, ]; } } ?> Now, whenever we create or update a user, its name property will be in uppercase. Step 3 − Add an actionTestBehavior function to the SiteController. public function actionTestBehavior() { //creating a new user $model = new MyUser(); $model->name = “John”; $model->email = “[email protected]”; if($model->save()){ var_dump(MyUser::find()->asArray()->all()); } } Step 4 − Type http://localhost:8080/index.php?r=site/test-behavior in the address bar you will see that the name property of your newly created MyUser model is in uppercase. Print Page Previous Next Advertisements ”;
Yii – Using Controllers
Yii – Using Controllers ”; Previous Next Controllers in web applications should extend from yiiwebController or its child classes. In console applications, they should extend from yiiconsoleController or its child classes. Let us create an example controller in the controllers folder. Step 1 − Inside the Controllers folder, create a file called ExampleController.php with the following code. <?php namespace appcontrollers; use yiiwebController; class ExampleController extends Controller { public function actionIndex() { $message = “index action of the ExampleController”; return $this->render(“example”,[ ”message” => $message ]); } } ?> Step 2 − Create an example view in the views/example folder. Inside that folder, create a file called example.php with the following code. <?php echo $message; ?> Each application has a default controller. For web applications, the site is the controller, while for console applications it is help. Therefore, when the http://localhost:8080/index.php URL is opened, the site controller will handle the request. You can change the default controller in the application configuration. Consider the given code − ”defaultRoute” => ”main” Step 3 − Add the above code to the following config/web.php. <?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”), ], //changing the default controller ”defaultRoute” => ”example”, ”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; ?> Step 4 − Type http://localhost:8080/index.php in the address bar of the web browser, you will see that the default controller is the example controller. Note − The Controller IDs should contain English letters in lower case, digits, forward slashes, hyphens, and underscores. To convert the controller ID to the controller class name, you should do the following − Take the first letter from all words separated by hyphens and turn it into uppercase. Remove hyphens. Replace forward slashes with backward ones. Add the Controller suffix. Prepend the controller namespace. Examples page becomes appcontrollersPageController. post-article becomes appcontrollersPostArticleController. user/post-article becomes appcontrollersuserPostArticleController. userBlogs/post-article becomes appcontrollersuserBlogsPostArticleController. Print Page Previous Next Advertisements ”;
Yii – Dependency Injection
Yii – Dependency Injection ”; Previous Next A DI(dependency injection) container is an object that knows how to instantiate and configure objects. Yii provides the DI container via the yiidiContainer class. It supports the following kinds of DI − Setter and property injection PHP callable injection Constructor injection Controller action injection The DI container supports constructor injection with the help of type hints − class Object1 { public function __construct(Object2 $object2) { } } $object1 = $container->get(”Object1”); // which is equivalent to the following: $object2 = new Object2; $object1 = new Object1($object2); Property and setter injections are supported through configurations − <?php use yiibaseObject; class MyObject extends Object { public $var1; private $_var2; public function getVar2() { return $this->_var2; } public function setVar2(MyObject2 $var2) { $this->_var2 = $var2; } } $container->get(”MyObject”, [], [ ”var1” => $container->get(”MyOtherObject”), ”var2” => $container->get(”MyObject2”), ]); ?> In case of the PHP callable injection, the container will use a registered PHP callback to build new instances of a class − $container->set(”Object1”, function () { $object1 = new Object1(new Object2); return $object1; }); $object1 = $container->get(”Object1”); Controller action injection is a type of DI where dependencies are declared using the type hints. It is useful for keeping the MVC controllers slim light-weighted and slim − public function actionSendToAdmin(EmailValidator $validator, $email) { if ($validator->validate($email)) { // sending email } } You can use the yiidbContainer::set() method to register dependencies − <?php $container = new yiidiContainer; // register a class name as is. This can be skipped. $container->set(”yiidbConnection”); // register an alias name. You can use $container->get(”MyObject”) // to create an instance of Connection $container->set(”MyObject”, ”yiidbConnection”); // register an interface // When a class depends on the interface, the corresponding class // will be instantiated as the dependent object $container->set(”yiimailMailInterface”, ”yiiswiftmailerMailer”); // register an alias name with class configuration // In this case, a “class” element is required to specify the class $container->set(”db”, [ ”class” => ”yiidbConnection”, ”dsn” => ”mysql:host=127.0.0.1;dbname = helloworld”, ”username” => ”vladimir”, ”password” => ”12345”, ”charset” => ”utf8”, ]); // register a class with configuration. The configuration // will be applied when the class is instantiated by get() $container->set(”yiidbConnection”, [ ”dsn” => ”mysql:host=127.0.0.1;dbname = helloworld”, ”username” => ”vladimir”, ”password” => ”12345”, ”charset” => ”utf8”, ]); // register a PHP callable // The callable will be executed each time when $container->get(”db”) is called $container->set(”db”, function ($container, $params, $config) { return new yiidbConnection($config); }); // register a component instance // $container->get(”pageCache”) will return the same instance each time when it //is called $container->set(”pageCache”, new FileCache); ?> Using the DI Step 1 − Inside the components folder create a file called MyInterface.php with the following code. <?php namespace appcomponents; interface MyInterface { public function test(); } ?> Step 2 − Inside the components folder, create two files. First.php − <?php namespace appcomponents; use appcomponentsMyInterface; class First implements MyInterface { public function test() { echo “First class <br>”; } } ?> Second.php − <?php appcomponents; use appcomponentsMyInterface; class Second implements MyInterface { public function test() { echo “Second class <br>”; } } ?> Step 3 − Now, add an actionTestInterface to the SiteController. public function actionTestInterface() { $container = new yiidiContainer(); $container->set (“appcomponentsMyInterface”,”appcomponentsFirst”); $obj = $container->get(“appcomponentsMyInterface”); $obj->test(); // print “First class” $container->set (“appcomponentsMyInterface”,”appcomponentsSecond”); $obj = $container->get(“appcomponentsMyInterface”); $obj->test(); // print “Second class” } Step 4 − Go to http://localhost:8080/index.php?r=site/test-interface you should see the following. This approach is convenient as we can set classes in one place and other code will use new classes automatically. Print Page Previous Next Advertisements ”;
Yii – Modules
Yii – Modules ”; Previous Next A module is an entity that has its own models, views, controllers, and possibly other modules. It is practically an application inside the application. Step 1 − Create a folder called modules inside your project root. Inside the modules folder, create a folder named hello. This will be the basic folder for our Hello module. Step 2 − Inside the hello folder, create a file Hello.php with the following code. <?php namespace appmoduleshello; class Hello extends yiibaseModule { public function init() { parent::init(); } } ?> We have just created a module class. This should be located under the module”s base path. Every time a module is accessed, an instance of the correspondent module class is created. The init() function is for initializing the module”s properties. Step 3 − Now, add two more directories inside the hello folder − controllers and views. Add a CustomController.php file to the controller’s folder. <?php namespace appmoduleshellocontrollers; use yiiwebController; class CustomController extends Controller { public function actionGreet() { return $this->render(”greet”); } } ?> When creating a module, a convention is to put the controller classes into the controller’s directory of the module”s base path. We have just defined the actionGreet function, that just returns a greet view. Views in the module should be put in the views folder of the module”s base path. If views are rendered by a controller, they should be located in the folder corresponding to the controllerID. Add custom folder to the views folder. Step 4 − Inside the custom directory, create a file called greet.php with the following code. <h1>Hello world from custom module!</h1> We have just created a View for our actionGreet. To use this newly created module, we should configure the application. We should add our module to the modules property of the application. Step 5 − 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”; $config[”modules”][”gii”] = [ ”class” => ”yiigiiModule”, ]; } return $config; ?> A route for a module”s controller must begin with the module ID followed by the controller ID and action ID. Step 6 − To run the actionGreet in our application, we should use the following route. hello/custom/greet Where hello is a module ID, custom is a controller ID and greet is an action ID. Step 7 − Now, type http://localhost:8080/index.php?r=hello/custom/greet and you will see the following output. Important Points Modules should − Be used in large applications. You should divide its features into several groups. Each feature group can be developed as a module. Be reusable. Some commonly used features, as SEO management or blog management, can be developed as modules, so that you can easily reuse them in future projects. Print Page Previous Next Advertisements ”;
Yii – Responses
Yii – Responses ”; Previous Next When a web application handles a request, it generates a response object, which contains HTTP headers, body, and HTTP status code. In most cases, you will use the response application component. By default, it is an instance of yiiwebResponse. To manage response HTTP status codes, use the yiiwebResponse::$statusCode property. The default value of yiiwebResponse::$statusCode is 200. Step 1 − Add a function named actionTestResponse to the SiteController. public function actionTestResponse() { Yii::$app→response->statusCode = 201; } Step 2 − If you point your web browser at http://localhost:8080/index.php?r=site/testresponse, you should notice the 201 Created response HTTP status. If you want to indicate that the request is unsuccessful, you may throw one of the predefined HTTP exceptions − yiiwebBadRequestHttpException − status code 400. yiiwebUnauthorizedHttpException − status code 401. yiiwebForbiddenHttpException − status code 403. yiiwebNotFoundHttpException − status code 404. yiiwebMethodNotAllowedHttpException − status code 405. yiiwebNotAcceptableHttpException − status code 406. yiiwebConflictHttpException − status code 409. yiiwebGoneHttpException − status code 410. yiiwebUnsupportedMediaTypeHttpException − status code 415. yiiwebTooManyRequestsHttpException − status code 429. yiiwebServerErrorHttpException − status code 500. Step 3 − Modify the actionTestResponse function as shown in the following code. public function actionTestResponse() { throw new yiiwebGoneHttpException; } Step 4 − Type http://localhost:8080/index.php?r=site/test-response in the address bar of the web browser, you can see the 410 Gone response HTTP status as shown in the following image. Step 5 − You can send HTTP headers by modifying the headers property of the response component. To add a new header to a response, modify the actionTestResponse function as given in the following code. public function actionTestResponse() { Yii::$app->response->headers->add(”Pragma”, ”no-cache”); } Step 6 − Go to http://localhost:8080/index.php?r=site/test-response, you will see our Pragma header. Yii supports the following response formats − HTML − implemented by yiiwebHtmlResponseFormatter. XML − implemented by yiiwebXmlResponseFormatter. JSON − implemented by yiiwebJsonResponseFormatter. JSONP − implemented by yiiwebJsonResponseFormatter. RAW − the response without any formatting. Step 7 − To respond in the JSON format, modify the actionTestResponse function. public function actionTestResponse() { Yii::$app->response->format = yiiwebResponse::FORMAT_JSON; return [ ”id” => ”1”, ”name” => ”Ivan”, ”age” => 24, ”country” => ”Poland”, ”city” => ”Warsaw” ]; } Step 8 − Now, type http://localhost:8080/index.php?r=site/test-response in the address bar, you can see the following JSON response. Yii implements a browser redirection by sending a Location HTTP header. You can call the yiiwebResponse::redirect() method to redirect the user browser to a URL. Step 9 − Modify the actionTestResponse function this way. public function actionTestResponse() { return $this->redirect(”http://www.tutorialspoint.com/”); } Now, if you go to http://localhost:8080/index.php?r=site/test-response, your browser will be redirected at the TutorialsPoint web site. Sending Files Yii provides the following methods to support file sending − yiiwebResponse::sendFile() − Sends an existing file. yiiwebResponse::sendStreamAsFile() − Sends an existing file stream as a file. yiiwebResponse::sendContentAsFile() − Sends a text string as a file. Modify the actionTestResponse function this way − public function actionTestResponse() { return Yii::$app->response->sendFile(”favicon.ico”); } Type http://localhost:8080/index.php?r=site/test-response, you will see a download dialog window for the favicon.ico file − The response is not sent until the yiiwebResponse::send() function is called. By default, this method is called at the end of the yiibaseApplication::run() method. To send a response, the yiiwebResponse::send() method follows these steps − Triggers the yiiwebResponse::EVENT_BEFORE_SEND event. Calls the yiiwebResponse::prepare() method. Triggers the yiiwebResponse::EVENT_AFTER_PREPARE event. Calls the yiiwebResponse::sendHeaders() method. Calls the yiiwebResponse::sendContent() method. Triggers the yiiwebResponse::EVENT_AFTER_SEND event. Print Page Previous Next Advertisements ”;
Yii – Theming
Yii – Theming ”; Previous Next Theming helps you replace a set of views with another one without the need of modifying original view files. You should set the theme property of the view application component to use theming. You should also define the following properties − yiibaseTheme::$basePath − Defines the base directory for CSS, JS, images, and so forth. yiibaseTheme::$baseUrl − Defines the base URL of the themed resources. yiibaseTheme::$pathMap − Defines the replacement rules. For example, if you call $this->render(”create”) in UserController, the @app/views/user/create.php view file will be rendered. Nevertheless, if you enable theming like in the following application configuration, the view file @app/themes/basic/user/create.php will be rendered, instead. Step 1 − 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”], ], ], ], ”view” => [ ”theme” => [ ”basePath” => ”@app/themes/basic”, ”baseUrl” => ”@web/themes/basic”, ”pathMap” => [ ”@app/views” => ”@app/themes/basic”, ], ], ], ”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; ?> We have added the view application component. Step 2 − Now create the web/themes/basic directory structure and themes/basic/site. Inside the themes/basic/site folder create a file called about.php with the following code. <?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 style = “color: red;”> This is the About page. You may modify the following file to customize its content: </p> </div> Step 3 − Now, go to http://localhost:8080/index.php?r=site/about, the themes/basic/site/about.php file will be rendered, instead of views/site/about.php. Step 4 − To theme modules, configure the yiibaseTheme::$pathMap property this way. ”pathMap” => [ ”@app/views” => ”@app/themes/basic”, ”@app/modules” => ”@app/themes/basic/modules”, ], Step 5 − To theme widgets, configure the yiibaseTheme::$pathMap property this way. ”pathMap” => [ ”@app/views” => ”@app/themes/basic”, ”@app/widgets” => ”@app/themes/basic/widgets”, // <– !!! ], Sometimes you need to specify a basic theme which contains a basic look and feel of the application. To achieve this goal, you can use theme inheritance. Step 6 − Modify the view application component this way. ”view” => [ ”theme” => [ ”basePath” => ”@app/themes/basic”, ”baseUrl” => ”@web/themes/basic”, ”pathMap” => [ ”@app/views” => [ ”@app/themes/christmas”, ”@app/themes/basic”, ], ] ], ], In the above configuration, the @app/views/site/index.php view file will be themed as either @app/themes/christmas/site/index.php or @app/themes/basic/site/index.php, depending on which file exists. If both files exist, the first one will be used. Step 7 − Create the themes/christmas/site directory structure. Step 8 − Now, inside the themes/christmas/site folder, create a file called about.php with the following code. <?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”> <h2>Christmas theme</h2> <img src = “http://pngimg.com/upload/fir_tree_PNG2514.png” alt = “”/> <p style = “color: red;”> This is the About page. You may modify the following file to customize its content: </p> </div> Step 9 − If you go to http://localhost:8080/index.php?r=site/about, you will see the updated about page using the Christmas theme. Print Page Previous Next Advertisements ”;
Yii – Query Builder
Yii – Query Builder ”; Previous Next Query builder allows you to create SQL queries in a programmatic way. Query builder helps you write more readable SQL-related code. To use query builder, you should follow these steps − Build an yiidbQuery object. Execute a query method. To build an yiidbQuery object, you should call different query builder functions to define different parts of an SQL query. Step 1 − To show a typical usage of the query builder, modify the actionTestDb method this way. public function actionTestDb() { //generates “SELECT id, name, email FROM user WHERE name = ”User10”;” $user = (new yiidbQuery()) ->select([”id”, ”name”, ”email”]) ->from(”user”) ->where([”name” => ”User10”]) ->one(); var_dump($user); } Step 2 − Go to http://localhost:8080/index.php?r=site/test-db, you will see the following output. Where() function The where() function defines the WHERE fragment of a query. To specify a WHERE condition, you can use three formats. string format − ”name = User10” hash format − [”name” => ”User10”, ”email => [email protected]”] operator format − [”like”, ”name”, ”User”] Example of String format public function actionTestDb() { $user = (new yiidbQuery()) ->select([”id”, ”name”, ”email”]) ->from(”user”) ->where(”name = :name”, [”:name” => ”User11”]) ->one(); var_dump($user); } Following will be the output. Example of Hash format public function actionTestDb() { $user = (new yiidbQuery()) ->select([”id”, ”name”, ”email”]) ->from(”user”) ->where([ ”name” => ”User5”, ”email” => ”[email protected]” ]) ->one(); var_dump($user); } Following will be the output. Operator format allows you to define arbitrary conditions in the following format − [operator, operand1, operand2] The operator can be − and − [”and”, ”id = 1”, ”id = 2”] will generate id = 1 AND id = 2 or: similar to the and operator between − [”between”, ”id”, 1, 15] will generate id BETWEEN 1 AND 15 not between − similar to the between operator, but BETWEEN is replaced with NOT BETWEEN in − [”in”, ”id”, [5,10,15]] will generate id IN (5,10,15) not in − similar to the in operator, but IN is replaced with NOT IN like − [”like”, ”name”, ”user”] will generate name LIKE ”%user%” or like − similar to the like operator, but OR is used to split the LIKE predicates not like − similar to the like operator, but LIKE is replaced with NOT LIKE or not like − similar to the not like operator, but OR is used to concatenate the NOT LIKE predicates exists − requires one operand which must be an instance of the yiidbQuery class not exists − similar to the exists operator, but builds a NOT EXISTS (subquery) expression <, <=, >, >=, or any other DB operator: [”<”, ”id”, 10] will generate id<10 Example of Operator format public function actionTestDb() { $users = (new yiidbQuery()) ->select([”id”, ”name”, ”email”]) ->from(”user”) ->where([”between”, ”id”, 5, 7]) ->all(); var_dump($users); } Following will be the output. OrderBy() Function The orderBy() function defines the ORDER BY fragment. Example − public function actionTestDb() { $users = (new yiidbQuery()) ->select([”id”, ”name”, ”email”]) ->from(”user”) ->orderBy(”name DESC”) ->all(); var_dump($users); } Following will be the output. groupBy() Function The groupBy() function defines the GROUP BY fragment, while the having() method specifies the HAVING fragment. Example − public function actionTestDb() { $users = (new yiidbQuery()) ->select([”id”, ”name”, ”email”]) ->from(”user”) ->groupBy(”name”) ->having(”id < 5”) ->all(); var_dump($users); } Following will be the output. The limit() and offset() methods defines the LIMIT and OFFSET fragments. Example − public function actionTestDb() { $users = (new yiidbQuery()) ->select([”id”, ”name”, ”email”]) ->from(”user”) ->limit(5) ->offset(5) ->all(); var_dump($users); } You can see the following output − The yiidbQuery class provides a set of methods for different purposes − all() − Returns an array of rows of name-value pairs. one() − Returns the first row. column() − Returns the first column. scalar() − Returns a scalar value from the first row and first column of the result. exists() − Returns a value indicating whether the query contains any result count() Returns the result of a COUNT query other aggregation query methods − Includes sum($q), average($q), max($q), min($q). The $q parameter can be either a column name or a DB expression. Print Page Previous Next Advertisements ”;