olhon.info Science Yii Application Development Cookbook Second Edition Pdf


Saturday, June 22, 2019

olhon.info Yii Application Development Cookbook Second Edition A eBook versions of every book published, with PDF and ePub iles available?. C, including most of the features included in the current ANSI standard. All of the programming SCHAUM'S OUTLINE OF T. When Alex told me he was about to write a Yii cookbook about a year ago, I was user-contributed Yii Application Development Cookbook, 2nd Edition.

Yii Application Development Cookbook Second Edition Pdf

Language:English, Spanish, German
Genre:Children & Youth
Published (Last):05.10.2015
ePub File Size:16.40 MB
PDF File Size:15.29 MB
Distribution:Free* [*Regsitration Required]
Uploaded by: JACINTO

Yii Application Development Cookbook Second Edition olhon.info K Addison - Developing Enterprise Java Applications with. Yii Application Development Cookbook, 2nd Edition - PDF Buy Yii Application Development Cookbook 2nd Revised edition by Alexander Makarov (ISBN. Name: Yii Application Development Cookbook, 2nd edition Format: PDF The second edition fixes all errata found in the first edition and also features new.

Reader feedback is important for us to develop titles that you really get the most out of. To send the author feedback about the book, simply ill in the form at http: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code To get the example code iles for this book visit http: Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you ind a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book.

If you ind any errata, please report them by visiting http: Once your errata are veriied, your submission will be accepted and the errata will be uploaded on the book website at http: At Packt, we take the protection of our copyright and licenses very seriously.

If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at copyright packtpub.

We appreciate your help in protecting our authors, and our ability to bring you valuable content. Questions You can contact the book's author at http: These are mostly described in the framework API, but since they are not mentioned in the oficial guide http: However, the features described here are relatively simple and using them makes development with Yii much more fun and productive. Using getters and setters Yii has many features that came from other languages, such as Java or C.

One of them is deining properties with getters and setters for any of the classes extended from CComponent that is, virtually any Yii class. How to do it As PHP does not have properties at the language level, we can only use getters and setters in the following way: This syntax is very common in the Java world but it is a bit long to use in PHP. Still, we want to use the same functionality that C properties gives us: With Yii, we can do it in the following way: Using this feature, you can make properties read-only or write-only while keeping the simple PHP syntax as follows: For example, when you call Yii:: How it works The following example shows what Yii 1.

If a method named getProperty exists, then PHP uses its return value as a property value. There's more For further information, refer to the following URL: An event is a message indicating that the application did something. We can register several event handlers that will react to certain event types. A handler can get parameters from an event it works with and react accordingly. Using events allows us to achieve great application lexibility.

In this recipe, you will learn how to declare and use both predeined and custom events in your application. To declare an event in your CComponent child class, you should add a method with a name starting with on. For example, if you add the onRegister method, you will get a corresponding event declared. A method used to declare an event becomes the default event handler.

Typically, events are used like this: To achieve it, we can use the CComponent:: It accepts the following two parameters: You should pass an array: For example, you can attach an event handler the same way as with attachEventHandler using the following code: As we now know how to deine and use handlers, let's review some real life examples as follows: If you have full access to your server, then you can conigure it to do so, but in some environments such as shared hosting, you don't.

In order to do so, we should start buffering the output when the application starts and release the gzipped output, when it completes. Let's use them. Insert the following code snippet in the index.

You can get them all by searching for the function on text in the framework folder using your favorite IDE. Now, let's look at another example. In Yii, you can translate strings to different languages using Yii:: As we all love perfect projects, all language translations should be up to date. If they are not, we would like to receive an e-mail about it.

Events come in handy again here.

In particular, the CMessageSource:: Let's assume we have a blog application and we need to send an e-mail when there is a new comment Comment to the blog post Post. Comment is a standard AR model generated with Gii. Post is the same Gii-generated model except for some customized methods.

We will need a custom event, NewCommentEvent, to store both Post and Comment models and a handler class, Notifier, that will do the work.

Destiny Disrupted: A History of the World Through Islamic Eyes

All standard AR methods are omitted to emphasize what was added: Now it is time to implement the Notifier class. After the comment has been added, admin will receive an e-mail about it. It is not always necessary to attach an event handler.

Let's look at how we can handle an event that is already declared inside an existing component by overriding a method of the base class. For example, we have a form model UserForm used to collect some information about our application user and we need to get the complete name from the irst and the last name entered by the user.

Fortunately, in CModel, which is the base class for all Yii models including form models, the CModel:: This method is called after a successful form validation. The CEvent class contains just two properties named sender and handled. The irst property contains an object that calls the current event, while the second can be used to prevent calling all other, not yet executed handlers, by setting it to false. The approach described here can be used to customize your Active Record models and implement your own model behaviors.

Further reading For further information, refer to the following URLs: Fortunately, you can do it automatically using the SPL class loader http: Autoloading is one of the features that Yii relies on. Still, there are many questions about it on the forums. Let's get it clear and show how we can use it. When we use a class, for example, CDbCriteria, we are not including it explicitly so PHP initially cannot ind it and tries to rely on the autoloading feature; the SPL autoloader, to be precise.

In most cases, the Yii default autoloader YiiBase:: It's done through the YiiBase:: Zii classes, such as CMenu, extension classes, or your own classes are not loaded automatically, so we need to import them irst. To import classes, we will use Yii:: Let's assume that we have a custom class named LyricsFinder that inds lyrics for a given song. We are trying to use it in the following way: When executing it, we will get the following PHP error: No such file or directory.

Yii helps us there a bit because at the error screen, we can see that the autoloader fails because it doesn't know where to look for our class.

Therefore, let's modify our code: LyricsFinder' ; 18 www. The built-in Yii class loader requires that each class should be placed into a separate ile named the same as the class itself. When developing using case insensitive ilesystems such as ones used by Windows, make sure you're using the same case in both the ilename and code since it can be a problem when you deploy your code to a case sensitive Linux server.

Let's look at application. The following table shows some more standard aliases: If LyricsFinder requires some additional classes located in its directory, then we can use Yii:: If you want your classes to be imported automatically like with Yii's core classes, then you can conigure global imports in your main.

Using exceptions Exceptions are a core PHP feature, but they are seldom used fairly. Yii makes exceptions very useful. There are two main areas where Yii exceptions come in handy, which are as follows: This is how we can use exceptions inside of it: Try again later.

For example, an action that displays a blog post represented by a Post model loaded by its ID will look like this: Additionally, the default exception handler raises either the onError event or the onException event.

The default event handler writes a log message with the error level set to error. This screen includes a call stack trace, a code area where the exception was raised, and the ile and line where you can look for the code to ix. For further information, refer to the following URLs: Moreover, as in every customizable code, there should be a convenient way to set up different application parts.

So in Yii, this is provided through a coniguration ile named main. How to do it… If you have worked with Yii before, then you have probably conigured a database connection: With the preceding coniguration, you can access a component by its name, such as Yii:: How it works… When you are using the Yii:: In the preceding code, the 'connectionString' value will be assigned to CDbConnection:: If you want to ind out what 'charset' stands for or want to know what else you can conigure in the db component, then you need to know its class.

In case of the db component, the class is CDbConnection. You can refer to its API page at http: It does not exist in the CDbConnection class. Therefore, it can be used to override a class as follows: MyDbConnection', … , … , … ; This way, you can override each application's component and it is very useful whenever a standard component does not it your application.

Now, let's ind out which standard Yii application components you can conigure. There are two application types bundled with Yii which are as follows: You can get the component names from API pages http: Both console and web application components are listed in the following table: Additional components available only for web application are listed in the following table: Component name Default component class Description session CHttpSession This component provides the session- related functionalities.

It also manages the cookies sent from and to the user. You can add your own application components classes extended from CComponent by simply adding new coniguration items and pointing their class properties to your custom classes.

For example, a widget can render a tag cloud or provide a custom form input type. Core widgets are highly conigurable and are used in views as follows: Note that we have changed the count of items per page to 15 in our example. If we want our pagination to display 15 items per page on all pages of our application, then we will need to provide a pageSize parameter with a value of 15 for all CLinkPager widget calls. Is there a better way?

Deinitely, yes. How to do it… A Yii web application provides a bunch of components. One of them is a widget factory that since Yii 1. Let's use it to set pageSize application-wide. We will need to edit the main.

Now, the default value for pageSize of CLinkPager will be 15, so if we omit this parameter for all the CLinkPager classes of the application then it will be 15, application-wide.

Moreover, we still can override the pageSize value for a speciic widget: You set the default overall style in an external ile, but can still override this through inline styles for individual widgets. See also f The Coniguring components recipe Using Yii core collections Yii has a set of collection classes used mainly for internal purposes which are not described in the deinitive guide, but are still very useful for applications: CQueue f Stack: It allows the use of collections like a standard PHP construct.

Compared to the native PHP array, it adds stricter checks, can be used in OO fashion, and allows to make a collection read-only: Just like in CList, it can also be used in the native PHP style, has almost the same set of OO methods, and allows making a collection read-only: A queue works as FIFO: In the same way as list and map collections, these can be used in native PHP style and have OO style methods: How to do it… You can access the request component in your web application by using Yii:: So, let's review the most useful methods and their usage, methods that return different parts of the current URL.

In the following table, the returned parts are marked with a bold font. Methods Results getUrl http: It can't be completely accurate, but it is good to use it as a fallback in case the user has not speciied a preferred language manually.

The MIME type, if not set manually as a third parameter, will be guessed based on the ilename's extension. It returns a CCookieCollection class instance that allows us to work with cookies. If you are working with a lot of cookie values and want to shorten the code provided, then you can use a helper as follows: You will be able to make your controllers and views more lexible.

Router rules description is scattered over the oficial Yii guide and API docs. Let's try to understand how to conigure application rules by example. Getting ready 1. Create a fresh Yii application using yiic webapp as described in the oficial guide http: It should contain the following: Delete everything from rules as we are going to start from scratch.

Conigure your application server to use clean URLs. After saving your changes, you should be able to browse the following URLs: Let's review what was done and why it works. We'll start with the rightmost part of the irst rule: In the Yii application, each controller and its actions have corresponding internal routes. So, in order to get the controller ID, you should take its name without the Controller postix and make its irst letter lowercase.

To get an action ID, you should take the action method name without the action preix and, again, make its irst letter lowercase. Now, what is home? To understand it in a better way, we need to know, at least supericially, what's happening when we access our application using different URLs. If the match is found, then the router gets the controller and its action from an internal route assigned to the rule and is executing it.

The fewer rules you have, the fewer checks are needed if the URLs do not match. Fewer URLs means more performance. You can also create parameterized rules using a special syntax. Let's review the third rule: You can deine a pattern for such a parameter.

We did it for the second rule: This is really useful because you can focus on internal routes while developing your application, and only worry about real URLs before going live. It will allow you to change URLs without rewriting a lot of application code.

Replace the rules array as follows: Depending on where we need it, there are different ways for doing it, but the basics are the same. Let's list some methods that generate URLs.

Post navigation

These use CHtml:: Therefore, you should pass data in one of the following formats: In this case, a URL will be generated 42 www. Each controller and its actions have corresponding routes. To get a controller ID, you should take its name without the Controller postix and make its irst letter lowercase.

In this case, the current module name and the current controller name are used: It tries to apply routing rules one by one, starting from the top. The irst matched rule is applied. If no rules are matched, then the default URL form is generated. We want our PostController action to accept parameters according to some speciied rules and give the not found HTTP response for all parameters that do not match.

Let's use regular expressions in the coniguration ile to achieve this: The following screenshot shows that the URL http: You can use regular expressions in both parameter deinition and the rest of the rule. Let's read our rules one by one. No other symbols are allowed. The order parameter can only accept two values: Note that regardless of the rule used, the developer should never assume that input data is safe. To learn more about regular expressions, you can use the following sources: Let's ind a way to create URL rules for these types of pages.

The most straightforward way is to deine a rule for each page, as follows: No problem, we can use default parameters to achieve it: What if we have many pages and want to be able to dynamically create pages without adding more rules or changing existing ones? We can achieve this with the following rule: In addition, default rules with one slug, such as controller name, will stop working.

To overcome this issue, we need to add default rules, which we deleted in the Getting ready section of this recipe. Let's read the rules we just wrote. The default parameter allows you to set a value that will be used if a parameter with a name speciied is omitted. When you need to specify an option for the rule, you should use an array notation: That means the URL manager will always stop at this rule and will never try to apply a default convention.

See also f The Coniguring URL rules recipe f The Using regular expressions in URL rules recipe Providing your own URL rules at runtime When you are developing an application with a pluggable module architecture, you most likely need to somehow inject your module-speciic rules into an existing application.

Set up a new application using yiic webapp. Generate the page module using Gii. You need to uncomment the gii section under modules and set a password. Then, open http: Don't forget to add your new module to the modules list in your application coniguration.

Create ModuleUrlManager. In your application coniguration ile, add the following line: Now, in your page module, you can add custom rules.

To do so, open PageModule. To test if it works, open your browser and go to http: This page should look like the one shown in the following screenshot: This is the view content for action "index".

The action belongs to the controller "DefaultController" in the "page" module. You can still override URL rules from your main application coniguration ile. So, what you specify in module's urlRules is used only when the main application rules don't match. Let's review the ModuleUrlManager:: If there are modules deined in our application, then we are checking if the urlRules public property exists. If it does, then there are some rules deined in the module and they are added using CUrlManager:: The CUrlManager:: In our index.

That is why we are attaching our class method to it. As instantiating all application modules on every request is not good for performance, it is good to cache module rules. Caching strategy can vary depending on your application. Let's implement a simple one: So, adding new modules is not a problem but changing existing ones requires you to lush the cache manually using Yii:: In Yii, it is not in the guide as you can achieve lexibility in many other ways.

Still, using a base controller is possible and can be useful. Getting ready We are going to set up a new application using yiic webapp. Let's say we want to add some controllers that will be accessible only when the user is logged in. We can surely set this constraint for each controller separately, but we will do it in a better way. First, we will need a base controller that our user-only controllers will use. Let's create SecureController.

You will get something like this: Now, your TestController index will be only accessible if the user is logged in, even though we have not declared it explicitly in the TestController class. The trick is nothing more than a basic class inheritance. If ilters or accessRules is not found in TestController, then it will be called from SecureController.

Using external actions In Yii, you can deine controller actions as separate classes and then connect them to your controllers. This way, you can reuse some common functionality.

For example, you can move the backend for autocomplete ields to an action and save some time by not having to write it over and over again. Another simple example that we will review is deleting a model. Create a database schema with the following script: Generate the Post and User models using Gii.

Add some data to the tables. It is a usual delete action for posts: One lists all posts and another deletes a speciied post if it exists and redirects back to the index action.

Now, let's do the same in a separate action class. Create DeleteAction. Let's use it inside our controller. Delete actionDelete; we will not need it anymore. Then, add the actions method: It should work exactly the same way as it did last time. Now, we are using the external delete action for PostController, but what about UserController? To use DeleteAction with UserController we need to customize it irst. We do this as follows: Now, we can use this action for both PostController and UserController.

For PostController, we do this as follows: For UserController, we do this as follows: This way, you can save yourself a lot of time by implementing and reusing external actions for tasks of a similar type.

Every controller can be built from external actions like a puzzle from pieces. The difference is that you can make external actions very lexible and reuse them in many places. In the inal version of DeleteAction, we deined some public properties. As DeleteAction is a component, we can set its properties through the coniguration ile.

In our case, we pass the coniguration into the action's controller method, used to add actions to a module. There's more… For further information, refer to the following URLs: Getting ready Set up a new application using yiic webapp. We just need to connect CViewAction to our controller. Now, you can try your pages by typing in the URL http: Alternatively, you can type in the URL http: If it is there, it displays it.

If not, then it will give you a not found page. There are some useful CViewAction parameters we can use. These are listed in the following table: Parameter name Description basePath This is a base path alias that is prepended to a view name. The default is pages. That means a page named faq. The default is index. By default, the controller layout is used.

If it is set to null, then no layout is applied. Otherwise, the PHP inside will be executed. The default is view. Further reading For further information, refer to the following URL: Typically, after some kind of action, such as editing a form, a redirect will happen and we need to display a message on the page we want to go to.

However, how do we pass it from the current page to the redirect target and clean up afterwards? Flash messages will help us.

Yii Application Development Cookbook, 2nd Edition

Now, if we go to http: Moreover, if we go to http: Refreshing the index page will hide the message. We set a lash message with Yii:: One of them is that you can use controller context in a view. So, let's try it. Create a controller as follows: Now, we will create a view showing what we can do: When doing it, we can call a controller method and access its properties.

The most useful property is pageTitle, which refers to the current page title. There are many built-in methods that are extremely useful in views such as renderPartials and widget.

Create WebsiteController as follows: Set up a database using the following SQL: Use Gii to generate the User model. Add some data to the user table. We will start with a reusable block. For example, we need to embed a YouTube video on several website pages. Let's implement a reusable template for it. You will get something like the following: Now, we need to make it reusable. We want to be able to set the video ID, width, and height.

Let's make the width and height optional, as follows: Now, let's send some e-mails. As we are unable to write unique letters to thousands of users, we will use a template but will make it customized. You can go check our new videos section.

There are funny raccoons. Yours, Website team. That's it. Note that you need to conigure PHP to be able to send e-mails. Instead you can just echo the result without actually sending it.

There's more… For further information, refer to the following URL: The basic idea is that you can record some output and then reuse it later in a view. A good example would be deining additional content regions for your layout and illing them elsewhere. For our example, we need to deine two regions in our layout: That is it! Now, we need to ill these regions somehow.

We will use a controller action for the beforeContent region. As for footer, we will set its content from a view. Now, when you open your website's index page, you should get your IP just before the page content and a "built with" note in the footer.

Chapter 4, Working with Forms, shows how Yii makes working with forms a breeze and documentation on it is almost complete. Still, there are some areas that need clarification and examples. Chapter 5, Testing Your Application, covers unit testing, functional testing, and generating code coverage reports.

Recipes follow a test-driven development approach. You will write tests for several small applications and then implement functionality. Chapter 6, Database, Active Record, and Model Tricks, is about working with databases efficiently, when to use models and when not to, how to work with multiple databases, how to automatically pre-process Active Record fields, and how to use powerful database criteria.

Chapter 8, Extending Yii, shows not only how to implement your own Yii extension but also how to make your extension reusable and useful for the community. In addition, we will focus on many things you should do to make your extension as efficient as possible. Chapter 9, Error Handling, Debugging, and Logging, reviews logging, analyzing the exception stack trace, and own error handler implementation. Chapter 10, Security, provides information about keeping your application secure according to the general web application security principle "filter input, escape output.

Chapter 11, Performance Tuning, shows how to configure Yii to gain extra performance. You will learn a few best practices for developing an application that will run smoothly until you have very high loads. Chapter 12, Using External Code, focuses on using third-party code with Yii.

Chapter 13, Deployment, covers various tips that are especially useful on application deployment, when developing an application in a team, or when you just want to make your development environment more comfortable.

All three are different in terms of syntax, features, and performance. In this chapter we will learn how to work with the database effi ciently, when to use models and when not to, how to work with multiple databases, how to automatically preprocess Active Record fi elds, and how to use powerful database criteria. In this chapter we will use the Sakila sample database Version 0. Be it a small website or a social network, at least some parts are powered by databases.

We will measure the execution time and memory usage to determine when to use these methods. Getting ready 1. Create a new application by using yiic webapp as described in the offi cial guide at the following URL: 2.

Download the Sakila database from the following URL: 3. Execute the downloaded SQLs; fi rst schema then data. Use Gii to create models for the actor and film tables.

At the bottom there are statistics that give information about the memory usage and execution time. Let's review the preceding code. The actionar action method gets model instances by using the Active Record approach. We then simply iterate over all the actors and for each actor over each fi lm. Then for each item, we print its name. The actionquerybuilder function uses query builder. We then add query parts one by one with from, join, and leftjoin. These methods escape values, tables, and fi eld names automatically.

The queryall function returns an array of raw database rows. Each row is also an array indexed with result fi eld names. We pass the result to renderrows, which renders it.

With actionsql, we do the same, except we pass SQL directly instead of adding its parts one by one.

The renderrows function renders the query builder. The DAO raw row requires you to add more checks and generally, it feels unnatural compared to rendering an Active Record result. Performance Extra features Best for Gii will generate models and relations for you.

Produces an array of properly nested models as the result. Higher memory usage and execution time compared to SQL and query builder. Quotes values and names automatically. Prototyping selects. Update, delete, and create actions for single models the model gives a huge benefit when using with forms. Produces raw data arrays as the result. Working with large amounts of data, and building queries on the fly. Not very suitable for building a query on the fly.

Produces raw data arrays as results. Complex queries you want to complete with pure SQL and have maximum possible performance. There's more In order to learn more about working with databases in Yii, refer to the following resources: See also The Using CDbCriteria recipe 12 Database, Active Record, and Model Tricks Defining and using multiple DB connections Multiple database connections are not used very often for new standalone web applications.

However, when you are building an add-on application for an existing system, you will most probably need another database connection. Create two MySQL databases named db1 and db2. Copy it, rename the db component to db2, and change the connection string accordingly. That is it. Book Description Key Features Learn how to use Yii 2 efficiently through clear examples and core features, and see how to use tests, create reusable code snippets, core widgets, deployment, and more This book provides you with a wide space for practice approaches and helps you to learn about the new Yii2 framework.

Understand the difference between the Yii 1. It works to streamline your application development time and helps to ensure an extremely efficient, extensible, and maintainable end product. Being extremely performance optimized, Yii is a perfect choice for any size project. However, it has been built with sophisticated, enterprise applications in mind. You have full control over the configuration from head-to-toe presentation-to-persistence to conform to your enterprise development guidelines.Now we will run a test and make sure it fails.

It is used to highlight Yii deinitive guide examples, and we can use it to do the same for our application. You can refer to the following sources to get more information about ixtures: For this purpose we need to execute the extra SQL query manually.

When developing using case insensitive ilesystems such as ones used by Windows, make sure you're using the same case in both the ilename and code since it can be a problem when you deploy your code to a case sensitive Linux server.