An avid proponent of Yii Framework and open source software, Charles has offers eBook versions of every book published, with PDF and ePub iles available ?. Like most PHP frameworks, Yii implements the MVC (Model-View-. Controller) architectural pattern and . 9meteolille.info . Yii excels over other PHP frameworks in that it is efficient, feature-rich and clearly - php YiiRoot/framework/meteolille.info webapp WebRoot/testdrive books, while in other languages, the word may not have different form (such as Chinese).
|Language:||English, Spanish, Arabic|
|Genre:||Science & Research|
|PDF File Size:||19.59 MB|
|Distribution:||Free* [*Regsitration Required]|
Qiang Xue, creator of the Yii framework; Alexander Makarov, and the .. Next, I converted the MultiMarkdown source to a PDF using Pandoc, which sup- ports its . Please help Bill Keck by spreading the word about this book on Twitter! The Yii 2 PHP framework is highly scalable and extensible, and .. in order to avoid line breaks from the wordwrapping in PDF and other formats. The Yii framework also uses the latest features of PHP, like traits and All the content and graphics published in this e-book are the property of Tutorials Point (I ).
With our knowledge of these methods, as an exercise, let's go back to our previous migrations and rewrite them to preserve our users across our schema change: First, let's roll back our migrations to properly simulate the scenario: Next, let's seed our database with some test data: If we take a look at our database, we'll see that the initial schema and data is now in place.
The new code blocks have been highlighted for easy viewing: Now we can rerun our migration. If successful, we should see our original migration run and an insert call executed for each user in our database. Finally, we can query our SQLite database to preview the updated schema and see our updated users: Quoting table and column names When writing database-agnostic SQL queries, properly quoting ield names can be problematic.
To avoid this problem, Yii2 provides the ability to automatically quote table and column names for you using the correct quoting rule for the speciic database in use. To automatically quote a column name, simply enclose the column name in square brackets: To execute these commands, we can use the execute method in general: Yii2 also provides convenient wrappers for insert , update , and delete , which enables us to write commands without having to write raw SQL.
These methods properly escape and quote table and column names and bind parameters on your behalf. For instance, we can insert a new user into a database as follows: We can also delete a user in our database using the delete method: Parameter binding The number one rule when working with user-submitted data is to never trust user-submitted data.
Any data that passes through our databases and has come from an end user needs to be validated, sanitized, and properly bound to our statements before they are executed against our database.
To help protect against SQL injection, Yii2 offers several different ways to bind parameters to our queries in a way that will ilter our injected SQL. These three methods are bindValue , bindValues , and bindParam.
The irst method, bindValue , is used to bind a single parameter to a token within our SQL statement. For example, we can rewrite the previous query as follows: Following the previous example, we can write the following to update multiple users without having to rewrite our query each time: This will protect you against future changes to your code.
Transactions When running multiple queries in a sequence, we often want to ensure that our database state remains consistent across these queries. Most modern databases support the use of transactions to accomplish this. In a transaction, changes are written to the database in such a way that they can be committed if everything went well or rolled back without consequence if any given query within the transaction failed.
In Yii2, this looks as follows: Yii's Query Builder allows us to write database-agnostic queries in a programmatic way. Consequently, queries written through the Query Builder are signiicantly more readable than their DAO counterparts. For example, we could simply query for all the users in our database in Query Builder using the following code: Query construction methods The basics of Query Builder involve the chaining of multiple query methods together.
These method names directly correspond with the SQL segment that they are named after. When working with Query Builder, the most common methods that you'll use will be the select , from , and where methods. For instance, the following queries are identical: If you choose to list the column names as a string, ensure that you do that consistently throughout your application. In the following examples, we'll use the array format. The select method also supports column aliases and table preixes, as shown in the next example: For instance, if we want to retrieve the user's complete name as a single ield, we can execute the following query: For instance, if we want to list all the irst names of our user's database, we can execute the following query: The from method Our previous examples have already illustrated the basic usage of the from method.
The from method can also be used to specify a table alias, as shown in the following example: The where method The where method speciies the where segment of our SQL query and can be used either in a string format, hash format, or operator format.
The string format The string format of the where method should always be chained with the addParams method in order to prevent SQL injection: Rather than passing a string as a parameter, we can instead pass an array of key values representing the column name and value.
For example, we can ind all the users in our database with the irst name of John who were in their 20s and who didn't have a listed pet name by running the following query: We will have to adjust our schema with a migration to add these ields to our database.
This would result in the following query: The operator format The last way to use the where method is to use the operator format. In general, the operator format takes the following format: As you can imagine, the where method can quickly become very bulky and complicated.
Rather than using the operator, you may ind your code more readable by using the andWhere or orWhere methods to chain multiple conditions together: For example, to sort all of our users in our database by age, we can construct the following query: When properly used together, these two methods form the basics of paginating through results: Yii2 supports these methods via the groupBy and having methods. After grouping our results with groupBy , we can then ilter our results with the having method, which behaves the same as the where method.
The following example will only show the number of users in our dataset who are over a speciied age: Joins and unions can be performed through query builder using the join and union methods. The join method has the following method syntax: For example, suppose we had a posts and users table.
We could join them as follows using the join method: The result would include all users joined with all the posts that they owned. Joins can also be performed by type using the shortcut methods rightJoin , leftJoin , and innerJoin.
Yii2 provides the following query methods to execute queries built with Query Builder. Most of the times when working with Query Builder, we'll want to fetch all the records in our database. Carefully consider using the all method if you have a large dataset, as the resulting query execution could take a long time to complete, and it could either hang or cause an error in your application. In other instances, it may be more beneicial just to fetch the irst row of a query.
To fetch the irst row, we can use the one method: To achieve this, we can use the exists method, which will return either true or false, indicating that data would be returned from the resulting query. To fetch scalar values with query builder, we can use the scalar method. For instance, if we want to know how old the oldest user is in our database using the MAX SQL method, we can use the following code to return an integer representing their age: To fetch the irst row of our results, we can use the column method: Consequently, an array of all IDs in our database will be returned.
It's important to remember when querying for data that you only query for the data you need. If you need all data, you query for it in iterative way such as to limit the memory required for each query. To keep the memory consumption low and to prevent our application from hanging, we can use either the batch or each method.
By default, both methods will fetch rows from the database. To change the number of rows to be fetched, simply change the irst parameter of each method: Think of this method as a query appended with a limit and an offset parameter, which will restrict the number of returned rows. Each iteration of the batch query will contain multiple results. Like the batch method, the each method can be used to reduce memory consumption as well, but it will iterate over the query row-by-row instead, which means that each iteration of the method will result in a single instance of our data.
The beneit of using data providers and data widgets over queries built via Query Builder is that they provide an interface to automatically deal with sorting and pagination. Active data providers can also be populated through Query Builder, as shown in the following example: For more information on these data providers, check out the Yii2 guide at http: Once we have fetched our data with a data provider, we can pass the resulting data to a data widget.
Data widgets in Yii2 are reusable building blocks used within views to create complex interfaces to interact with data. In some instances, there may be sensitive data that we don't want to display on this page. Alternatively, there could simply be too much data to display in GridView. To restrict the number of ields to display in our GridView widget, we can use the columns attribute: More information on output data widgets can be found in the Yii2 guide at http: While some widgets, such as GridView, allow us to work with and display multiple rows, we can also use data providers and data widgets to display information for a single row.
With the DetailView widget, we can dynamically conigure a simple interface to display the information for a particular user in our database. The getModels method of our data provider splits our data provider into individual models that our DetailView widget can understand: This will be displayed on our screen: In addition to simply displaying results from a database, the DetailView widget also supports the custom formatting of certain rows.
More information on the formatter can be found at http: When working with large systems, we will split our database into a read-and-write master and a read-only slave of a set of slaves. Typically, our applications are unaware of our database architecture, which can introduce problems when required to migrate from a new master. With Yii2, we can conigure our database connection to not only be aware of our master-slave database coniguration, but also intelligently handle slave unavailability.
In Yii2, we can conigure a single master and multiple slaves using the following database coniguration. This will result in all writes going to our declared master and all reads going to one of our declared slaves: When working with slaves, Yii will attempt to connect to slaves in the list until a slave responds and load balance queries against each of the available slaves. By setting PDO:: Alternatively, using the following coniguration, we can conigure our application to work with both multiple masters and multiple slaves.
When using multiple masters, Yii will execute writes against any available master and will load balance writes between the available masters: When working with a master-slave topology, we may want to issue a read query against one of our masters. To do that, we would need to explicitly tell Yii2 to run our query against our master rather than our slaves: If we need to issue a transaction against a slave, we will need to explicitly begin the transaction on a slave, as follows: By working with database access objects, we showed how we can execute raw SQL statements to run against our database and how we can use transactions to protect our database integrity.
We also illustrated the use of Query Builder, which can enable us to write database-agnostic queries in a programmatic way. We then discovered how we can use Query Builder to construct intelligent data providers, which are used to supply data to reusable data widgets. Finally, we learned how to conigure Yii2 to be aware of master-slave and multi-master database cluster conigurations and how to load balance between these connections.
In the next chapter, we discover the capstone of working with databases in Yii2—Active Record—which is a powerful tool used to work with our data and model our database structure. We'll also dive into Active Records relatives, basic models, and forms, and we'll learn how we can use a powerful tool called Gii to automate the construction of much of the code our modern applications will work with.
These classes enable us to abstract our data management code away from DAO and Query Builder and into an easy-to-use programmatic interface.
In this chapter, we'll cover the use and implementation of Active Record and learn how to create data models and custom forms. We'll also cover how to conigure a powerful code generation tool called Gii to automate the creation of Active Record models and forms. Coniguring Gii While Active Record models and forms can be generated by hand, in most cases, we'll want to automate the creation of this code.
To achieve this, Yii2 provides a code generation tool called Gii, which can be executed both from the command line and from a web interface in order to create Active Record models that work with our database structure and forms that work with both our base models and Active Record models. In Yii2, nearly every module is available as a separate Composer package, which can be installed from the command-line interface.
Consequently, we must use Composer to include Gii in our application. Since Gii is available as a composer package, we can include it in our application by running the following command from our command line: Typically, during our deployment process, we'll use the --no-dev lag to ensure that development packages are not deployed to our production environment.
With Gii installed, we now need to conigure it to work with both the Yii2 console and within our web browser. While this basic coniguration will properly load the Gii module, it doesn't follow our convention of being aware of our environment. For instance, if we went to production with this coniguration and deployed it with composer install --no- dev, as described earlier, our application would crash because Composer would not have installed the Gii module in our vendor folder. Define in.
Gii for console applications Unlike Yii1, Gii for Yii2 provides a new interface to work with Gii on the command line. With Yii2, we can now generate the source code for Active Record models, forms, and even extensions all from our command-line interface.
As we move through the rest of the chapter, we'll cover how to use Gii from the web interface as well as the console interface. Active Record One of the most important tasks when building rich web applications is ensuring that we properly model and represent our data in code. From a simple blog site to an application as big as Twitter, data modeling and representation are vital to ensuring that our application is easy to work with and can grow as required. The Active Record pattern Named by Martin Fowler in his book Patterns of Enterprise Application Architecture, the Active Record pattern is an object-relational mapping ORM pattern that's used to represent database rows and columns within an object.
In the Active Record pattern, each database column is represented by a single Active Record class. Upon instantiation, that object then provides a simple interface to manage individual rows or a collection of rows within our code.
New rows can be created, old ones can be deleted, and existing rows can be updated—all within a simple and consistent API. Active Record also enables us to programmatically reference and interact with related data, which is usually represented in our database by foreign key relations.
In this section, we'll cover how to create new Active Record classes, how to implement them within our code, and some common pitfalls of working with Active Record.
Before we start working with Active Record, we irst need to create a couple of tables that we can work with.
Included with the project resources for this chapter is a base migration that will create several new tables and populate them with some sample data: In Yii2, app is a predeined alias that points to our application base path.
If we want to, we can declare additional aliases, such as frontend and backend, to divide our application into different sections, which would enable us to create multiple Active Record instances in different namespaces.
Finally, we need to implement the static method tableName within our class, which deines the table name our Active Record model will use. Since our Active Record model will use the user table, we will deine this method as follows: Using Gii to create our Active Record classes has several advantages: From this page, we can generate Active Record classes based upon our database schema.
As an example, let's create an active record instance for our user table: First, we need to populate the Table name ield with user, the name of the user table in our database.
As you type, Gii will try to show you possible database tables that match our text entry, which can be extremely beneicial when working with large databases. Next, we need to either press the Tab key on our keyboard, or focus our mouse onto the Model name ield, which should autopopulate the ield with User, which will be the name of the class that Gii will generate.
Then, we need to ensure that the Generate Relations checkbox is selected. This will automatically add the required code to our class in order to generate our model relations for the Post and Role classes, which we'll create in the next section. After checking this box, our form should be illed as follows: Then, we can click on the Preview button at the bottom of the page, which will enable us to preview the code that Gii will generate for us before we conirm the creation of our class.
In our Linux environment, this can be done by adding the www-data group to the folder and adjusting the permissions so that the user can write to it: Just ensure that you readjust the permissions to something more reasonable after using Gii to create the model. All of these ields are conigurable within the Gii web interface for us to change. Using Gii's console interface As an alternative to Gii's web interface, Gii can generate Active Record classes from the command line.
When running Gii from the command line, we simply need to provide two attributes: This takes the following form: As shown in the previous code block, it has marked both the email and password attributes as required and the email ield as unique, and it has correctly identiied the appropriate data types for our name ields as well as timestamps. Adding custom validators In addition to the many built-in core validators Yii2 has, we may need to write our own custom validators for our classes.
Custom validators can either be written inline using anonymous functions, or they can be written as a separate method within our class. For instance, suppose we only want to permit changes to our user information between certain core hours of our business. As an anonymous function, this can be written as follows: However, if we want to alter the error message for a certain property, we can do that by specifying the message parameter for a speciic validator.
For instance, we can adjust the error message for our unique validator by changing the last line of our validator to the following: As shown in the previous example, this takes the following form: This method will return an array of errors containing an array of error messages applicable for each attribute: While this can be done manually in our controller, it is typically executed before the save method is executed.
The validator method will return either true or false, indicating whether the validation was successful or not. Model attribute labels The next method that Gii automatically implements for us is the attributeLabels method. The attributesLabels method enables us to name our model attributes with more descriptive names that we can use as form labels. By default, Gii will automatically generate labels for us based upon our column names.
Furthermore, by following the convention of using underscores in our column names in our user table, Gii has automatically created titleized and readable attribute labels for us: We'll cover the Yii:: Active Record relationships Assuming that we conigured our database schema properly with primary and foreign keys, Yii2 will also generate model relationships for us. Our User model illustrates this for the Post and Role relationships: For instance, if we want to retrieve the name of the role for a user we are working with, we can simply execute the following: Check whether your relationships map to the correct classes and have the correct relationship types before executing your code.
Using multiple database connections with Active Record By default, all active record instances will use the db component to connect to our database. In the instance where we have multiple databases connected to our application, we can conigure active record to work with an alternate database by deining the static method getDb within our Active Record class: To use a behavior with an Active Record class in Yii2, we simply need to specify that we want to use the behavior class at the top of our PHP ile and then add the behavior to the behaviors method of our model.
Like most things in Yii2, this is completely conigurable. Working with Active Record Now that we have learned what Gii automatically provides for us when creating new Active Record classes and what additional options we can add to our classes to enhance them, let's take a look at how we can use active record instances to perform basic create, read, update, and delete CRUD actions.
Both methods accept a scalar argument, an array of scalar arguments, or an array of associative pairs to query data: One way to get around this limitation is to convert our resulting data into an array format using the asArray method: While the asArray method can be used to increase the performance of large queries, it has several downsides.
The data returned will not be an instance of Active Record, and thus, it will not have any of the methods or helpful attributes associated with it. Moreover, since data is being returned directly from PDO, the data will not be typecast automatically and will be returned as a string instead.
Data access When using Active Record, each row from our database query will generate a single Active Record instance. The column values from our Active Record instance can be accessed via the model attributes for that Active Record instance: For instance, to retrieve the author's name from a given post, we can run the following code: If having Active Record attributes with underscores doesn't match your coding style, you should rename your column names.
Our data can also be manipulated by creating a custom getter and setter method within our Active Record class. For instance, if we want to display the user's complete name without changing our database schema, we can add the following method to our User Active Record class: If we retrieved our user information from the database again, we would see that the results were stored: Typically when using the load method, we'll provide data from a form submission, which we'll cover later in this chapter.
The post method represents any data submitted via a POST request. Creating new records Creating new records in our database can be done by instantiating a new instance of an active record class using the new keyword, populating the model with data, and then calling the save method on the model.
The delete method will permanently delete data from the database and will return true if the deletion was successful or false if an error occurred. A mistake in the conditional can result in an entire table being truncated.
Active Record events As an alternative to creating before and after method handlers such as beforeSave and afterDelete , Yii2 supports several different events that our application can listen to. The events that Active Record supports are outlined in the following table: For instance, if we want to create a model called UserForm to collect user information, we can write the following class: Calling unset on the class or creating a new instance of the class will not grant user the access to the data stored in other instance of the model.
Since our model attributes are public properties of our PHP class, we can access them like any public property. Scenarios When working with models or active record classes, we may want to reuse the same model for different situations, such as logging in a user or registering a user. To help us write less code, Yii2 provides the scenarios method to deine what business logic and validation rules should be executed for each scenario.
By default, scenarios are determined by our validation rules using the on property in our validation rules: The default scenario marks all model attributes as active for both mass assignment and model validation.
When working with models and active record instances, this is the preferred way to generate forms. Generating forms with Gii Like Active Record classes, forms can be generated automatically for us from both the web Gii tool and the console Gii tool. Let's take a look at generating a form for authentication, which we'll call LoginForm, and a form to handle registration, which we'll call RegisterForm.
For forms, we only need to know the view name which will translate to the ilename and the model class. Since we want to use our form just to log in, we should also specify that we want to use the login scenario. When specifying the model class, we need to specify both the namespace and the class so that Yii can ind our class.
Once we have speciied all the necessary attributes, we can click on the Preview button to preview our form, and then we can click on the Generate button to generate the source code. To pass a backslash character to Gii, we need to escape the backslash character with a second backslash. Here's the output: Our resulting RegisterForm view will look as follows: Remember to use the help tool to discover other command-line arguments for additional customization.
Using forms Now that we've created our forms, let's take a brief look at how exactly they work. In most cases, this is going to be deined in our controller and then passed down to our view: In Yii2, generated forms are intended to be rendered as a partial view rather than a complete view. Rather than specifying our form, LoginForm, directly in our controller, we will pass our model down to a parent view, which will then render our form.
As an example, our login action within our controller will change to the following: Instead, it has two separate render methods: Chapter 8, Routing, Responses, and Events, will help us gain a better understanding of how routing works in Yii2 and how we can easily igure out which controller actions match to which view actions.
ActiveForm and input types Now that we know how to render our form, let's break down our form view. Since view iles and controllers are separated in Yii2, we need to irst make sure that we use our active form class in our view ile: To customize these, we can provide an array of arguments to our begin method to manually specify these attributes: Since the method is chainable, we can chain additional attributes onto our form.
For instance, if we want to add client-side validation for our email ield so that our browsers can verify our text ield was an email address, we can chain the following: We covered how to properly set up and conigure Gii, the code generation tool for Yii2.
We then covered how we can automatically create Active Record classes based upon our database schema using both the web and console interface for Gii in addition to many of the common methods and properties we can bind to our Active Record classes, such as validation rules, attribute labels, and behaviors.
Next, we covered how to create basic models that do not depend upon our database and how to add scenarios to our models and Active Record classes. We inally covered how we can use the Gii tool to create HTML forms based upon our models and explored some of the functionality that comes with the ActiveForm class. In the next chapter, we are going to expand our knowledge of the available helpers and widgets that come with Yii2.
We will also dive into modules in Yii2 and explore how we can use them to create reusable self-contained applications that we will keep building upon throughout the book. As we move forward, we are going to build upon much of the knowledge we have gained thus far. Before moving forward, ensure that you review the classes and information we have learned about. Yii2 also provides us with the ability to build and include mini applications known as modules that can enable us to rapidly add new features to our application while maintaining a clear separation of concerns in our main application and any extended functionality.
In this chapter, we'll cover the basics of building and working with modules within our application. We'll also cover several of Yii2's built-in widgets and helpers and learn how we can implement our own custom widgets. Modules In Yii2, modules are considered to be mini self-contained software packages containing the complete MVC stack.
When paired with an application, modules provide a way to extend applications by adding new features and tools without adding code to our main code base. Consequently, modules are a great way to create and reuse code.
When creating applications with Yii2, you'll most likely work with prebuilt models, such as Gii or the Yii2 dev module; however, modules can also be custom applications created speciically to build upon and separate code for a speciic purpose. In this section, we'll go over the basic modules in Yii2 as well as cover how to create and implement them within our application.
At their core, they still consist of the same structure and share many of the same ideas. In Yii2, modules are stored in the modules directory of our application root and are registered with our application through our web or console coniguration iles.
If we were to break down a basic module, its directory structure and core iles would be as follows: Consequently, any controller within the module, unless otherwise registered with our URL manager, will be available as a dedicated controller route within the module itself.
For example, the DefaultController. Additionally, modules provide full support for the basic MVC architecture within Yii2. Each module may have its own set of models, views, controllers, and even components. Like complete applications, modules also have support for their own views and layouts, allowing them to be styled and managed differently than our main application. As part of a Yii2 application, they also have complete access to the models and classes implemented within our main application.
The module class structure The most important part of a module is the module class deined in the Module. Additionally, custom conigurations can be registered to our module using the Yii:: This coniguration can be a simple key-value pair, or it can be a complete coniguration ile, such as those used in our web and console coniguration iles.
The Yii2 coniguration syntax can be explored in detail in the Yii2 guide located at http: For instance, if we have a controller to handle users called UserController, we can make our default route map to our controller, as follows: Remember that unless otherwise speciied, controllers will always be available in their named URI.
To get started with rendering our view, we irst need to deine which layout we want to use. For more information on these methods, refer to the layout section of the Yii2 documentation at http: After deining our layout, we'll need to deine the view ile for our DefaultContro ller:: For now, let's simply add the following to this view ile: Hello World!
Any key- value pair will populate the public property of the speciied class with the value listed in the array.
Dynamically registering modules Often when working with large projects, several components will be broken down into modules that need to be registered with our application.
Moreover, there may be circumstances where only certain modules need to be registered at a given time. One way to automate the process of registering many different modules at once is to create a dynamic coniguration script and let our application scan our modules for us.
First, we'll want to set the directory that we want to scan as well as try to load a precached coniguration ile, should one exist. Then, we'll try to return our cached coniguration ile, should it exist. Finally, we generate a cached version of our generated coniguration ile to eliminate duplicate work on each request.
Bootstrapping modules Some modules, such as the debug module, need to be executed on every request when enabled. To ensure that these modules run on every request, we can Bootstrap them by adding them to the Bootstrap section of our coniguration ile.
If you're familiar with Yii1, the bootstrap option is used in a manner similar to the Yii1 preload coniguration option: The Bootstrap parameter of our coniguration option will ensure that Yii2 will autoload and register the object early on in the execution low rather than waiting until the class it requires. Be careful with adding items to the bootstrap section, however, as forcing Yii2 to register objects before they're needed can introduce performance degradation into your application.
Accessing modules When working with modules, you may need to get the instance of the currently running module to either access the module ID and parameters or components associated to the module. To retrieve the current active instance of a module, you can use the getInstance method on the module class directly: Using Composer and semantic versioning, we can manage our modules such that they are versioned to speciic points in time in our application while still enabling developers to work with us.
Moreover, we can also conigure our main project to automatically install modules for us on deployment, which can drastically reduce the overhead involved in managing modules: To get started with managing our modules with Composer, we irst need to move our module source code out of our main application and push it to our DCVS repository.
Next, we need to create a composer. Portwood II", "homepage": To automatically install modules to our modules directory, we need to explicitly declare the type of our Composer package.
The composer-installers project does not support Yii- specific modules currently; however, for our purpose, the drupal-module type does what we need. Next, we'll need to make some changes to our main projects' composer. The irst change we need to make is the inclusion of the composer- installers dependency. We can do this by adding the following to the require block of our composer. The second change we need to make to our main project's composer. We can do this by creating a repositories block populated with the DCVS information for our module repository and then adding the module to our require block: Then, we need to add the installation information to the extras section of our composer.
This provides the required information to the composer- installers package: Then, we'll want to ensure that our module directory is excluded from our DCVS repository.
We can do this adding a. Finally, we can run Composer to update and automatically install our module: During deployments, however, you should semantically version your module so that the versioned copy of the module is downloaded rather than cloned. Our module has now been installed from Composer. Modules in summary Modules are best used in large applications where certain features or reusable components need to be created. As we've shown in this section, modules are extremely powerful and can be used to extend our application.
Widgets In Yii2, widgets are reuseable code blocks that are used in views to add conigurable user interface logic to our application in an object-oriented way. Yii2 comes with several different types of reusable widgets, some of which we have already seen in previous chapters. Custom widgets can also be created to create tools that can be reused across multiple projects.
In this section, we'll go over the basic types of widgets, how to use them, and how to implement our own within our applications. In Yii2, widgets can be used in one of two distinct ways. This method takes a coniguration array as an option and returns a rendered widget as a result.
Using our previous example, this will look as follows: Commonly used built-in widgets To help quickly develop applications, Yii2 comes with several powerful widgets built in that we can use to jumpstart development.
Bootstrap widgets One of the main widget types Yii2 provides is speciic to Twitter Bootstrap 3 styles and provides a quick and easy way to add a functionality to our application. However, this can be optimized by including the core Bootstrap assets within our application's asset manager, AppAsset. These core widgets are as follows: More information on Twitter Bootstrap 3 can be found at http: Support for jQuery UI widgets can be added to our application by including the yii2-jui Composer package in our application: More information on jQuery UI can be found at https: Yii-speciic widgets Yii2 comes with support for familiar Yii1 widgets such as ActiveForm and GridView, both of which we explored in previous chapters.
MaskedInput An input widget used to force users to enter properly formatted data Menu A widget used to display a Yii menu Spaceless A widget to remove whitespace characters between HTML tags Several online projects also exist to extend Yii2's widget collection. Before trying to implement your own widget, try to search Yii2's extensions to see whether someone might have already implemented what you need.
Creating custom widgets In some instances, it may make more sense to create our own widget to handle a speciic task. For instance, suppose we want to create a widget that displays a greeting with the user's name depending upon the time of the day. We can create that widget by implementing the following: As an illustration, let's create a widget that outputs whatever is wrapped within a begin and end tag in an HTML div element. We can write this class as follows: In Yii2, widgets have native support for the render method, allowing us to render view iles.
A summary of widgets Widgets are powerful object-oriented reusable code blocks that we can add to our views to quickly and easily add additional functionality to our application. As self-contained objects, widgets follow the MVC pattern and handle dependency management for any and all assets and external scripts required for the widget to function. In this section, we'll go over several of the more common helpers. Comprehensive documentation for all helpers Yii2 supports can be found on the Yii2 API documentation page underneath the helpers section at http: To retrieve the home URL of your application, use the home static method.
Several different arguments can be passed to get different types of URLs: The URL helper can also be used to generate routes to other parts of your application using the toRoute and to method. In general, the toRoute method takes the following form: The to method is identical to the toRoute method, except that it always expects an array rather than a string: When passed without arguments, the current URL will be returned.
Any array arguments passed to the method will generate the current URL with its parameters: In general, HTML tags can be generated by calling the tag method, as follows: Any piece of data submitted by the end user should be wrapped within the encode method to prevent XSS injection. The addCssClass method can work with either a string or an array deinition of a class, and it will not add a class if it already exists: A complete method list is available at http: It's recommended when using Yii that you use this class instead of the native PHP functions.
VarDumper can be used as follows: Several examples of inlector are provided as follows: To search for iles in a given directory, we can use FileHelper, as follows: With the ind iles method, we can specify the ile type we want to have or exclude: To disable this behavior, we can set the recursive attribute to false: We irst covered the basics of a module, its MVC structure, and how to integrate it into our main application.
We also covered how to use Composer to automate the inclusion of modules in our projects for development as well as deployment. We then covered widgets in Yii2 and learned how we can use them in our application. We also covered how to create our own widgets.
Finally, we covered several of the built-in helpers in Yii2 and learned how to use them. We'll also cover how we can integrate other tools, such as Grunt, Node, and Bower, to simplify the use of our assets in Yii2. Second only to functionality, the presentation of our application might be considered the most important aspect of our application. Presentation of our user interface and the corresponding user experience is vital to building excellent web applications.
With raw HTML, we can include any necessary scripts and styles we need to, however often we need to handle our assets in a programmatic way such as when using modules, components, or widgets.
To help manage our assets, we can use a combination of third-party tools and Yii2's built-in asset manager. In this chapter, we'll cover how to use Yii2's asset management tools, as well as cover several third-party tools we can use to simplify management of our asset iles. Asset bundles Assets in Yii2 are managed through an asset bundle. Since our default application comes within a pre-deined AppAsset class, let's take a look at what is already deined in that ile.
Setting this property will override basePath and baseUrl. Then during the view rendering stage, it will generate all the necessary HTML markup to be included in our view. If we wanted this asset bundle to use a different version of jQuery, or wanted to improve performance by using a third-party CDN, we could override the jQuery asset bundle options as follows. Alternatively, we can also conditionally redeine which iles are rendering, say in the instance where we have a miniied version of a script we want to display in production, but a non-miniied version we'd like to use in other environments.
Additionally, we can disable speciic asset bundles by setting that bundle to false, as shown in the following example. For example, one asset bundle may include jQuery version 2. To resolve these conlicts, we can set the assetMap property of our coniguration ile to resolve any named instances of an asset ile to a single dependency that will be included in our view. The assetMap property matches on the last part of an asset ile within bundles as a key-value pair.
Asset types and locations Depending upon their location, Yii2 will classify an asset in one of three different ways. Assets will be classiied as a source asset, a published asset, or an external asset. Source assets are asset iles that are mixed in within our source code and are not in a web-accessible directory.
Such assets are often included with modules, widgets, extensions, or components. Any assets that Yii2 deines as source assets will need to be published by Yii2 to a web-accessible directory. Published assets are source assets that have been published to a web-accessible directory. And inally, external assets are assets that are located in a web-accessible location, such as on our current server or on another server or CDN.
Unlike published assets, Yii2 will not publish these assets to our assets directory, and will instead reference them directly as an external resource. When working with asset bundles, if the sourcePath property is speciied, Yii2 will consider any assets listed with a relative path as a source asset, and will attempt to publish those assets during runtime.
If the sourcePath property is not speciied, Yii2 will assume the listed assets are in a web-accessible directory and are published. In this case, it is necessary to specify either the basePath property, or the baseUrl property to tell Yii2 where the assets are located. Any data stored in this directory could be removed at any time by Yii2. To apply different conditionals to each asset individually, you'll need to create a separate asset bundle deining those conditionals, or inline the assets within the view using theregisterCssFile or registerJsFile methods.
As previously mentioned, the publication path can be altered by setting the baseUrl and basePath properties of the asset bundle. To help alleviate this problem, Yii2 provides two alternatives. Rather than copying over iles, Yii's asset manager can be conigured to create a symbolic link between the origin asset iles and the web-accessible directory by setting the linkAssets property of assetManager as follows: Once Yii2 has published our assets, it won't publish them again unless we remove our assets directory or tell Yii2 to republish our assets.
By default, Yii2 will run the publication process on every ile listed in the sourcePath property, which means if you have a large directory then every ile will be copied over regardless of whether it is actually used. To have Yii2's asset manager only copy over the iles you need, you can modify the publishOptions property of the asset bundle. Take for instance if we're using Yahoo's popular CSS library, purecss.
To build purecss from source, we need to run Bower, NPM, and Grunt, which will leave behind build iles we shouldn't publish to our web directory. By setting the publishOptions property as shown in the following example, we can ensure only the build iles are published, which can drastically improve performance during initial publication. When pushing out new code, often our assets will change, but their ile locations will not, which will prevent clients from receiving our updated assets when we make changes.
The simplest way to overcome this issue is to append a version or timestamp to the end of our assets so that browsers can cache a speciic version of our assets, and be able to re-cache new assets as we push to them.
With Yii2, we can conigure our asset manager to automatically append the last modiied timestamp to our assets by setting the appendTimestamp property of our assetManager as follows: Yii2 can help facilitate this process by enabling asset manager to take care of this build process for you. Take for instance the following asset bundle: Yii2 is dependent upon the corresponding pre-processor software to be installed on your computer for this feature to work. To set this in Yii2, you can set the converter property of our assetManager instance as follows.
When working in production, it's usually a better idea to build all of your asset iles on a build server before pushing your application out to production. We'll cover how to build asset iles with Grunt, NodeJS, and Bower later on in this chapter, and cover some basic deployment strategies in Chapter 13, Debugging and Deploying.
Yii2 can help facilitate this process through the asset command, which can help you use Yii2, and some third-party Java tools to compress and combine your asset iles. Please define these: You will need to install both of these tools for the asset command to function as intended. This coniguration ile deines several different options. By default, these tools will try to use Closure Compile and YUI Compressor; both can be conigured as needed if you wish to use other tools.
The second option, bundles, deines the asset bundles that you wish to compress together. The third option, assetManager, deines some basic options that the asset manager component should use, such as the basePath and baseUrl for the compressed assets. Finally, the targets option deines the output asset bundles that will be generated.
By default, Yii2 will create a target called all, and will generate compressed assets for all asset bundles listed. As the frontend assets don't need to be included with our backend assets, we can deine multiple targets, which will generate separate assets after compression, allowing us to include those assets speciically, thus saving bandwidth for our end user. An example is shown as follows: While Closure Compiler and YUI Compressor are good tools, tools like Grunt and NodeJS can often provide a solution that is easier to work with and develop for, while eliminating much of the coniguration you need to do in Yii2 to compile and compress assets.
When working with assets, be sure to ind a tool that works best with your development worklow, team, and build process.
Third-party asset tools When working with modern web applications, we often need to include many different types of asset from various sources. Including these assets directly in our application can cause several problems, namely: With Yii2, we can work directly with Node and Bower packages.
In this next section, we'll take a look at three tools: To get started with node, we'll irst need to download the software from https: For our purposes, NodeJS will provide us with the tools and packages that we need to automatically download and build our asset iles. To get started with NodeJS, we irst need to include a package.
This ile will deine all the dependencies we want to use. A typical NodeJS ile for asset management will look as follows: The irst way is to include them as dependencies within our package. This is advantageous as we can version lock our build tools to our application. Alternatively, we can globally install these tools so that we can run them directly through the command line. When working with many developers and teams, it's generally better to use the tools as deined in the package.
With our NodeJS coniguration ile setup; we can now use NodeJS to add these tools to our repository by running the following command: Since this directory contains build tools, we should exclude it from our repository by adding it to our.
To get started with Bower, we irst need to create a bower. We can do that by writing out a basic bower. While this eliminates many of the issues listed previously, we can alternatively use another third-party tool called Grunt to take care of compressing and concatenating our iles together.
When programming in PHP, we often have to solve problems that are already developed by others. Remember to configure our applications, connect to the database, display the templates - all of this must be programmed by yourself. It is very easy to use the framework, which contains most of the elements we need. Simply turn them on and configure them in the settings file. This allows you to start working on the system you want to program.
Framework Yii has in its resources: Additionally, Yii is equipped with a module called Gii - it allows for automatic generation of elements such as controller, model or entire CRUD management systems. Using the framework we will build an application based on the MVC pattern, which will sort different elements of the application and in the future there will be no problem with finding the right fragment of the code. By using models with queries to databases, views containing page templates and controllers containing program code, we create a solution that is consistent with developers' practices all over the world.
Additionally, Yii has an element called ActiveRecord, thanks to which the creation of simple queries to the database does not have to be done in the model. For this purpose it is enough to use controller where appropriate methods are used to create a query. The framework will process them on request in SQL language.