Web Application Development with Yii 2 and PHP Fast-track your web . Did you know that Packt offers eBook versions of every book published, with PDF and ePub .. In the prior versions of Yii, you had to manually download and extract the. Editorial Reviews. About the Author. Jeffrey Winesett. Jeffrey Winesett has over ten years of Download it once and read it on your Kindle device, PC, phones or tablets. Use features like bookmarks, eBook features: Highlight, take notes, and . Download PHP and MySQL® Web Development, Fourth Edition Fast-track your web application development using the new generation Yii PHP framewo.
|Language:||English, Spanish, Hindi|
|Genre:||Politics & Laws|
|ePub File Size:||19.77 MB|
|PDF File Size:||16.30 MB|
|Distribution:||Free* [*Free Regsitration Required]|
Read "Web Application Development with Yii 2 and PHP" by Mark Safronov available from Rakuten Kobo. Sign up today and get $5 off your first purchase. A step-by-step tutorial to Yii, it talks you through the development of a Web Application Development with Yii and PHP Book Cover Download this Video course in MP4 format; DRM FREE - read and Print + eBook. new generation Yii PHP framework. Web Application Development with Yii 2 and PHP Book Cover Print + eBook. Start a FREE day trial.
Author s: Dmitry Eliseev , Andrew Bogdanov Pages: PDF Catetories: 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.
Cyber Security. Full Stack. Game Dev. Git and Github. Technology news, analysis, and tutorials from Packt.
Stay up to date with what's important in software engineering today. Become a contributor. Go to Subscription. You don't have anything in your cart right now. Yii is a high performance PHP framework used for rapid web application development. It is well designed, well supported, easy to learn, and easy to maintain. This book embraces the learn-by-example methodology to show you the most important features of the Yii 2 framework.
Throughout the course of this book, you will build a simple real-world application; each chapter will introduce you to a new functionality and show you how to tweak your application. Instead of trying to be an all-encompassing reference about the framework, this is a walkthrough of the really important pieces of information that you have to understand in detail. You will learn how to use Yii's active record and CRUD scaffolding to manage the data in your database.
Authentication, extensions, events and behaviors, and route management are just some of the many other features of Yii that you will learn from this book. By the end of this book, you will have a basic CRM application that is all set for service! Mark Safronov is a professional web application developer from the Russian Federation, with experience and interest in a wide range of programming languages and technologies.
He has built and participated in building different types of web applications, from pure computational ones to full-blown e-commerce sites. He is also a proponent of following the current best practices of test-first development and clean and maintainable code.
He was also a maintainer of the popular YiiBooster open source extension for some time. Back in , he translated the book Visual Prolog 7. Jeffrey Winesett is a partner at SeeSaw Labs in Austin, Texas, and has over 10 years of experience building large-scale, web-based applications. He is a strong proponent of using open source development frameworks when developing applications, and a champion of the Yii framework in particular since its initial alpha release. He frequently presents on, writes about, and develops with Yii as often as possible.
Sign up to our emails for regular updates, bespoke offers, exclusive discounts and great free content. Log in. My Account. Log in to your account. Not yet a member? Register for an account and access leading-edge content on emerging technologies. Register now. Packt Logo. My Collection. Deal of the Day Create dynamic dashboards to bring interactive data visualization to your enterprise using Qlik Sense.
Sign up here to get these deals straight to your inbox. Find Ebooks and Videos by Technology Android. Packt Hub Technology news, analysis, and tutorials from Packt. Insights Tutorials. News Become a contributor. Categories Web development Programming Data Security. Subscription Go to Subscription. Subtotal 0. Title added to cart.
Subscription About Subscription Pricing Login. Features Free Trial. Search for eBooks and Videos. Fast-track your web application development using the new generation Yii PHP framework. Are you sure you want to claim this product using a token?
that help you master the framework
Mark Safronov, Jeffrey Winesett September Quick links: What do I get with a Packt subscription? What do I get with an eBook? What do I get with a Video? Frequently bought together. Learn more Add to cart. Paperback pages. Table of Contents Chapter 1: Getting Started. I would like to thank the Super Mario team dev team for all their support and help in producing this book.
Rashidul Hasan Masum is a professional Software Engineer. Over the last 6 years, he has designed and developed a wide range of desktop and web applications using the enterprise framework Spring. His core competency lies in complete end-to-end management of a new application development. He also has experience in the following areas: He now works at OnnoRokom Software Ltd.
From the beginning, they have been using the Yii framework for their large-scale web application development. Quamruzzaman Rahmani www. The three of them are a super combination for teamwork according to their personality proiles. I'd like to thank Venitha Cutinho and Akash Poojary for their coordination.
Also, I'd like to thank my friend Maruf Maniruzzaman who works at Microsoft. He has taught me a lot about computer engineering. Thank you to my friend K. Masum Habib. I'd also like to thank Packt Publishing. I have read lots of e-books published by Packt Publishing.
He has 4 years of experience in working with the Yii framework in a variety of small and enterprise projects. You can upgrade to the eBook version at www. Get in touch with us at service packtpub. At www. TM http: PacktLib is Packt's online digital book library. Here, you can access, read, and search across Packt's entire library of books. Why subscribe? Simply use your login credentials for immediate access. Table of Contents Preface 1 Chapter 1: Getting Started 7 A basic application 7 Installation of a basic application template 7 Speciics of the basic application template 9 An advanced application 10 Installation of an advanced application template 11 Speciics of the advanced application template 13 Summary 14 Chapter 2: User Authentication Anatomy of the user login in Yii Password-based login mechanics in general Making the user management interface Acceptance tests for the user management interface Database table to store user records Generating the model and CRUD code by Gii Removing the password ield from the autogenerated code Hashing a password upon saving a user record Functional tests for password hashing Password hashing implementation inside the active record Making a user record into an identity Making the login interface Speciications of user authentication Making the authentication indicator The login form functionality The logout functionality and wrapping things up Summary Chapter 6: Collaborative Work Coniguration construction Adding local overrides to the coniguration Console application Custom console commands Database migrations Making custom templates for database migrations Summary Appendix A: Deployment Setup with Vagrant Planning Initial setup Fine-tuning the virtual machine Preparing the guest OS Preparing the database and web server Preparing the application Using the virtual machine as a local deploy target Appendix B: The Yii framework, hosted at http: It is suitable for building both web and console applications, but its feature set makes it most useful for web applications.
It has several code generation facilities, including the full create-read-update-delete CRUD interface maker. It relies heavily on the conventions expressed in its default coniguration settings. Overall, if all you need is a fancy interface for the underlying database, there is probably nothing better for you than the Yii framework. Given the extensive coniguration options, any kind of application can be made from Yii.
Version 2 of the Yii framework is built utilizing the latest improvements in the PHP infrastructure collected over the years. It uses the Composer utility see https: At the time of writing, Yii 2 is at the stage of late beta.
Some changes are expected, but there should not be backward-compatibility-breaking changes anymore. Thus, the content of this book can be reasonably trusted even if the framework can attain some additional features after this book is published. What this book covers Chapter 1, Getting Started, covers the simplest possible methods to raise a working web application completely from scratch using the Yii framework.
Preface Chapter 2, Making a Custom Application with Yii 2, shows how the process of implementation of a web application with a single, working, tested feature can be done from scratch using the Yii framework.
Chapter 3, Automatically Generating the CRUD Code, shows how we can implement a working, tested feature in an existing web application using only the code generation facilities and not a line of custom code written. Chapter 4, The Renderer, describes the details of how the framework renders its output and presents some tricks to introduce customizations to the rendering process.
Chapter 5, User Authentication, discusses the tools to provide authentication to application visitors. Chapter 6, User Authorization and Access Control, explains the ways to control access for application visitors, and, especially, about the role-based access control system. Chapter 7, Modules, returns from the exact features of the framework to its fundamentals.
Here we will clearly understand the internal structure and logic of the Yii-based application and how it inluences the overall design. Chapter 8, Overall Behavior, is about the infrastructure of the Yii-based application.
We will learn about several features that affect the application as a whole. Chapter 9, Making an Extension, tells us how to make the extension to the Yii 2 framework and prepare it so that it is installable in the same way as the extensions built-in to the basic distribution of the framework itself.
Chapter 10, Events and Behaviors, investigates the intricacies of the system inside the Yii 2 framework allowing us to attach custom behavior to many of the usual activities of the application, such as fetching a record from the database or rendering a view ile.
Chapter 11, The Grid, has two purposes. First, it explains the powerful and complex GridView widget, which allows you to make complicated, table-based interfaces relatively easily. Second, it presents a different approach in developing applications using the Yii 2 framework, the one that is customary in its community, so you can see both the advantages and the disadvantages of both approaches. Chapter 12, Route Management, explains the top level of the framework, that is, how it responds to HTTP requests from actual visitors.
Chapter 13, Collaborative Work, concludes the book by presenting the methods that help to manage the code base of a Yii-based application when there are several developers working on it. It was excluded from the chapter text because it's not directly related to the GridView widget, but we could not gloss over it completely. Through the course of the book, starting from Chapter 2, Making a Custom Application with Yii 2, we'll be working with a single code base. Later chapters will build over the work previously done, so the book is expected to be read sequentially, without skipping or changing order.
Who this book is for The text is targeted at existing, established developers who want to learn quickly whether the Yii framework can it their demands and, especially, worklow.
It is not a reference, but rather a guide. More than that, the reader is expected to have a copy of the source code and an oficial documentation as supplementary material while reading.
We will expect some relatively high qualiications from the reader, as several basic development concepts such as POSIX-compatible command line, version control system, deployment pipeline, automated testing harness, and an ability to navigate through the code base by fully qualiied names of classes are assumed as obvious and not requiring any explanation. If the reader is capable enough, then any of these requirements can be swapped for different vendors, except PHP, which is quite obvious.
You have to use PHP Version 5. Even if you don't update anything, you'll download approximately MB of libraries, so mobile Internet probably will not cut it. Conventions In this book, you will ind a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text, database table names, folder names, ilenames, ile extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: Tips and tricks appear like this.
Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback packtpub.
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 on 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 You can download the example code iles for all Packt books you have purchased from your account at http: If you purchased this book elsewhere, you can 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 our website, or added to any list of existing errata, under the Errata section of that title.
Any existing errata can be viewed by selecting your title from 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 us at questions packtpub. The goal is to learn about the installation procedure of the Yii application boilerplates offered by developers and the starting set of features provided in them. A basic application The most basic and straightforward way to get started with Yii 2 is to use the application boilerplate published by the Yii 2 team on their GitHub repository https: In the prior versions of Yii, you had to manually download and extract the archive with the framework contents.
While you can still do the same in Yii 2, this version is carefully crafted so that it's especially simple to install it using the Composer tool. Installation of a basic application template Find a suitable directory in your hard drive and fetch the Composer PHP archive PHAR into it in any way suitable for you, for example, using the following command: You probably will need to consult the composer.
Web Application Development with Yii 2 and PHP
But in any case, Composer will tell you what you need to install to make Yii 2 workable. Yii 2 gets new updates quite often and its requirements are a moving target. It's a line split into two lines for readability, with a slash denoting the overlow of the command line to the next line of text.
Shell interpreters on Unix-like systems should understand this convention, so you can probably just copy and paste the code verbatim and it'll be executed correctly.
Inside the basic folder will be your application root. After Composer inishes installing the required packages, you can just issue the following command: This will launch the web server built into PHP. This is not the preferred setup for PHP-based web applications, of course.
The built-in web server was used only as a "smoke test" to verify that everything in general works. It is suitable only for local development without a heavy load. The next chapter will deal with the real-world deployment of a Yii-based web application.
Point your web browser at the http: You should see the welcome page for the Yii 2 application, which means that you're done setting things up.
The most important thing you should understand is that the publicly available web root directory is just one folder in the overall code base. It's the web directory for our basic application. Every other folder is outside the web root directory, that is, out of reach for the web server.
As you have already seen in the installation description, given that you have PHP and, optionally, curl, this code base is ready to use right from the start; no speciic environment is needed to be set up. All the dependencies are managed through the Composer tool.
It contains acceptance, functional, and unit tests covering most of the functionalities. The tests already included in the template are useful as examples that show how to utilize the testing framework used, which is Codeception http: The template can be really useful to you if all you need is something like a news feed feature or a web tool spanning a couple of pages.
However, the absence of separation by subsystems, such as the administrative backend and public frontend, will start to hinder you on a larger web application; probably, an application with more than just 10 unique routes. Note that by reading the project dependencies in the composer.
These packages are listed as follows: Most probably, you'll need all of these on any serious project though. A short overview of the basic application installation: It's geared more towards medium-sized applications such as applications that are really useful to businesses , and its main feature is two separate web interfaces: So, you get an almost complete CMS skeleton with this template. You need to fetch the Composer executable and set up a new project using it: Now, let's make further changes.
First, go to the newly created directory named advanced. After this, you need to generate the required local coniguration by running the following command: It'll ask you whether you want a development mode or a production mode and create all the necessary auxiliary coniguration snippets and entry scripts. To be precise, it just copies the contents of the dev or prod folders from the environments subdirectory depending on whether you selected the development environment or the production one.
Just open the environments subdirectory and you'll understand how it works. Next, you need to create the database to be used by this application. By default, for coniguration of a development environment, you have to set up a MySQL database named yii2advanced accessible from the localhost at the default MySQL port for user root without any password. Given that you have the database set up, you need to run migrations.
We'll talk about migration scripts in the next chapter and we will even write several scripts ourselves , but if the very concept of database migrations is foreign to you, you can read about it in the oficial documentation at the Yii 2 website at the time of writing this, there is no oficial documentation, but the framework has the docs included in the GitHub repository at https: Just run the following command anyway: Now, you are ready.
Make both the sides of the application accessible for you by executing the following commands: Now you'll have the backend side of the application intended to be used by content managers and the frontend side of the application intended to be the website your visitors will see. Also, note that you have a completely controllable console runner launched by the yii script you used when doing migrations.
Advanced application has exactly the same frontend as basic application. Here is how its backend looks like: After logging in, you get the same page as the one from the basic template or the advanced template frontend, but with only the login feature in the menu. Speciics of the advanced application template The most important thing about the advanced application template is that it is three basic application templates wired together as one: Real functionalities and the content of your website or web application is expected to be placed here.
You are expected to place all of your admin-accessible CRUD here. Of course, nobody forces you to use the frontend and backend sides as described. You just have two web frontends sharing the same code base, so you are free to use them as you wish.
However, the UI already prepared for the advanced template that has a password-protected backend right from the start. You should know about the login feature for the freshly installed advanced application template.
Initially, it had no users deined, and you had to create one by utilizing the signup feature at the frontend. After that, you'll be able to login to both backend and frontend using the created credentials. The frontend is identical to the basic application, and the backend is stripped of everything except the login feature and front page, so everything is up to you.
A short overview of the installation of the advanced application: By utilizing the PHP 5. This will surely be quite tedious to do though. In the next chapter, we'll look at how we can utilize Yii in a albeit small real-world project, built completely from scratch, and without using the templates we saw in this chapter.
The example will be reasonably small, but it will be done using proper software engineering disciplines. We'll go through all the steps of application development, each step backed by the bleeding-edge best practice described in the deinitive books on this topic: This is explained in Domain-Driven Design: This is explained in the following books: This is explained in depth in the following books: This its into the Continuous Delivery paradigm too, but these steps are inevitable anyway Stay focused.
The design stage Pay attention to the fact that we will be using this example application through the whole book. In this section we'll deine the landscape for the whole adventure before us. Task at hand Let's pretend we are a small business providing some services. We have a particular number of clients we have connections with, and the amount is so large that managing it on paper and business cards is too unwieldy. So, we need some sort of automated way of inding the full proile about a given client.
For starters, we need some sort of create-read-update-delete CRUD user interface for simple records describing the most essential attributes of our clients. It's obvious that as we as a business will grow and evolve, the same will happen with our client management, and so our application will grow and evolve too. We should account for changes right from the start. As we will be eating our own dog food, this software better be of the highest possible quality.
Domain model design Obviously, we will be dealing with customer models in our application. Between the "customer" and "client" terms, we choose "customer" for accuracy.
A customer is a person who has a name, address, e-mail, and phone number at the minimum. We provide services for customers, which are counted in hours, and we are being paid fees for these hours according to the contract. That's what we will include in the irst iteration of designing. The name is an incredibly complex construct; if we are to delve into the details of its structure, such as honoriics, titles, nicknames, middle names, patronymics, and so on.
But we aren't really interested in the structure of the customer's name, we need it only for identiication purposes. So, we will represent it as a line of text, allowing us to write a name in free format. The address is a construct of the same complexity, but this time we have to retain the structure instead of using plain strings again, because we will need to do two things with addresses: Also, a customer can have many addresses.
The phone entity has the following attributes: Also, taking note of a birthday would be cool too. And e-mail, of course. By the way, a single customer can have several e-mails. Let's stop here. We can now igure out the complete aggregate for the customer model, which is depicted in the following diagram: Everything else is a value object, that is, an object whose state will not change after initial creation, and thus they are completely interchangeable.
For the sake of simplicity, we will not detail how business is done with the customer, because we will just not be able to cover it all across this book. However, let's mention that we have some sort of services we provide to our customers, and it'll be useful to maintain records of them too. This model will be used in the following chapter. Target feature Let's fulill one speciic task. Given that someone called us by phone assuming we have identiied the number , we want to get all the details we have gathered so far about the person who's calling.
If we don't have such a number associated with someone registered in our application, then we know he or she is not our customer yet. If we do have the number registered, then we can at least greet this person by his or her name, which is superb customer service.
Thus, our feature set for the irst iteration of development will be as follows: We will only deal with the queries containing a phone number. Let's begin then. Initial preparations We will be working on the same application in all of the following chapters until the end of the book, so the preparations are to be done only once.
Thus, we will start with a folder named crmapp. Please note that all examples of command-line invocations through the whole book assume that your current working directory is the crmapp folder and not anywhere deeper or higher in the ilesystem hierarchy. Version 2 of Yii has the Composer package manager as the preferred method of installation, so we will use this tool too.
While you can read the details in Composer's full documentation, here's a crash course of it: As long as you have the dependencies declared there, you can safely purge the vendor folder at any time as it'll be repopulated by the next call to php composer.
The documentation for Composer presents a nice one-line command that will get the Composer executable to you: After that, Composer will be invoked whenever composer. The code bundle for this book uses Git http: The reasons behind this decision are as follows: Yii 2 has support for the Codeception testing framework built-in, with http: We will never use it in this book, but the extension named yii2-codeception see https: Let's declare that we want Codeception available in our project.
Run the following command: Here are the contents of your composer. Of course, we'll need to add Yii 2 as a dependency at some point, but for now, let's do one thing at a time. Now, we have the Codeception executable available at. This location is a bit long to type, so a POSIX- compatible shell like bash allows you to reduce it as follows: In all of the following command-line examples in this chapter, we assume you have done this substitution. Codeception is a complex system, so we'll need to rely on its self-building system for now.
To not delve unnecessarily into the inner workings of Codeception, let's just stick to defaults. Call the following command: When you open it, you'll see something like the following, depending on the version of Codeception: Codeception also has CodeGuy for unit tests and TestGuy for functional tests, but that's for later. When we say AcceptanceTester. Let's change the dummy test to a simple smoke test that our landing page is up for: Let's pretend that we'll have such a title somewhere in there.
Now we run the test: Thus, we arrive at the point where we need to write production code to satisfy our tests. However, right now, it's not the production code we need, but the infrastructure to serve it.
We need a machine to deploy to. Setting up the deployment pipeline The problem is described here. The web acceptance tests that we will be writing imitate a real user who opens the web application in the browser and interacts with it using the visible UI. So, for them to work, we need an application that is fully deployed to somewhere accessible from the machine on which we will run acceptance tests. Don't do it. Most probably your own workstation is not the same as the machine your web application will ultimately run on.
This has been an ongoing problem in the industry for decades now, and you can be sure that when your application's lifetime is measured in years, you will get the same integration problems if you test your application on the machine with a different environment than the production server. Of course, this doesn't apply to the prepackaged software that you sell to various users and when you require portability.
In our case, we assume a stationary web application for a single deploy point, so portability is not an issue, but reproducible tests are an issue. Ultimately, your acceptance testing will consist of the following steps: Deploy the application to the test server.
Run acceptance tests on your machine. Of course, you can run acceptance tests on the test server. To do so, you just need to conigure tests to use the usual loopback network interface, localhost.
However, it will require you to install additional software for your test server irrelevant to the application itself. For example, if you decide to run full-stack, in-browser tests using Selenium, you'll probably need to install a web browser, Java runtime, and virtual framebuffer software on the test server, and this will lead to installation of a signiicant amount of system-related libraries, which probably is just a waste.
It's a lot more eficient to use your own desktop environment to run the web acceptance tests. This cannot be said about unit and functional tests, of course. Unit tests, due to their nature, are run on the raw code base, without the need to deploy at all. Functional tests should be run on the deployed application because they are required to test the validity of interactions between the conigured and working parts of the inal application. In any case, ideally you should end with a simple command, named something like deploy, which will do the following: Access and launch the target machine especially if it's a virtual machine instance.
Ensure that there is a valid environment expected by the application. Copy the current state of the code base to the target machine. Conigure the copied code base for the environment on the target machine. Launch the application. You should be able to do all of the preceding steps by typing deploy in the command line and hitting Enter.
As Martin Fowler said in his deinitive article Continuous Integration seen last time at http: Ideally, deployment should happen automatically when you launch the acceptance test harness. In this book, we'll concern ourselves with only the last two steps of the procedure. As we're working with a PHP application, the "launch the application" step typically will be completed as soon as we have a web server running on a target machine.
This is a book about web application development and not about system maintenance, and it's targeted at web developers and not operation engineers. However, in Appendix A, Deployment Setup with Vagrant, we prepared the description of one setup based on the usage of a virtual machine, which you can easily repeat on just any desktop workstation.
You will not need a separate physical machine, and you will still be able to imitate a real-world deploy procedure. If you don't have other options, you are strongly encouraged to read it.
Books | Yii PHP Framework
In fact, all of the code in this book was prepared using the setup described there. Let's pretend that you have an environment prepared with a deploy command, and for simplicity, we assume it'll be run before each run of the acceptance testing suite.
The result of your deploy should be the single URL accessible from your machine, which the acceptance testing harness will use as the entry point to your application. The ile, assuming you did not modify anything else and nothing has changed in the default Codeception installation since this chapter was written, should look like the following: AcceptanceTester modules: As we change the coniguration, we should rebuild the Codeception harness.
Here is the command to do it: The real executable is in the. If you run the tests now: It'll either be a error or error, depending on the version of Apache used, or maybe something else if you are using a different web server. Anyway, the root of the problem is simple, that is, we need an index. For example, if your web server is Apache, it'll be the web folder's path that you put into the DocumentRoot directory.
Given that, just put the following content as the index. Our CRM Yes, just a seven-character text ile. After all, that's everything our acceptance test expected, right? Then we run the tests: Now we need to allow ourselves to use Yii 2 in our project. An easy way to do this is just to write the full, end-to-end test, which describes our desired functionality. Introducing the Yii framework into our application Now that we have the entire supporting infrastructure we need to begin working with, let's return to our irst feature we deined at the design stage and deine the acceptance test for it.
We don't have any way of direct access to the database or, worse, ilesystem around the application. So, to test a query for some data in the database, this data should be inserted into the database irst.
And it should be done using the UI. Here are the resulting test steps: Open the UI for adding customer data to the database. Add customer 1 to the database. You should see the Customer List UI with one record. Add customer 2 to the database. You should see the Customer List UI with two records now. Open the UI to query customer data by the phone number. Query using the phone number of customer 1. You should see the query results UI with data for customer 1 but not for customer 2.
So, this test forces us to have three user-interface pages: That's part of why it's called "end-to-end" testing. Translated to the Codeception acceptance test suite, the procedure just described will look like this: This is our goal for the current chapter. Let's go over the not-so-obvious things in this test script. First, we broke down the scenario into two logical parts and made two different subclasses of AcceptanceTester to stress this distinction.
Just hit Enter there without writing anything to tell it that you want to start afresh. This helper is used to support the StepObject pattern see http: Of course, it's a lot more natural to reason about the subclasses of AcceptanceTester as having different roles than having some abstract containers of steps.
However, if we forcefully rename the generated classes, removing the unnecessary sufix, we would lose the auto-loading ability that Codeception automatically provides us with, so we'll just tolerate it. Now, let's deine the steps mentioned in the test scenario.
Almost all of these high-level steps will just be the containers of the more low-level steps built-in with the acceptance tester shipped with Codeception. First, we will see the CRM operator steps. Such placeholder data can be generated in any way. We'll be using the amazing Faker library https: However, we'll look into that a bit later.
But what ields should be there? Let's return to our Customer aggregate and see what parts of it we crucially need to fulill our test scenario: Of course, we don't take into account the Contract aggregate at all. For the task to be any "interesting", we include all the unique parts of the customer: Name, Birthday, and Notes.
Do remember that Name is a structure and not just a line of text like Notes. Please pay attention to the naming of form ields; it's not arbitrary and corresponds to our future database schema and the Yii 2 model's coniguration. Have a look at the following table: We cannot implement features until we have a basic test done for it, and our test does not explicitly check the ability to enter several phone numbers yet. First of all, let's bring the Faker library into our project: With all these methods deined in the CRMOperatorSteps class, we now have the irst half of our test case completed which means runnable.
Let's get done with the test steps for a CRM user, who'll do the querying. First, the obvious one is as follows: Lastly, here are our assertions: Quite an important question is why we don't check for the customer data being shown in the Customer List UI after each addition of a new customer.
After we query for the phone number, we end up in the same Customer List UI after all. Well, for now, the reasoning is dead simple: Also, the existence of some assertions halfway through the test case would violate the Single Assertion principle explained in detail in Clean Code, Robert Martin, Prentice Hall.
However, as this is the end-to- end acceptance test, doing this is probably not such a bad thing. Anyway, nothing prevents us from extending this test further again, it's an acceptance test imitating the behavior of a real user , but for now, let's stick with this simple scenario.
If you run the completed test scenario now, you should get the following error message: Scenario Steps: We have inally arrived at the Yii 2 installation procedure. First of all, you need to declare Yii 2 as a dependency of your application. Either add the required require line for Yii 2 manually in the composer.
Checking the requirements Yii 2 includes an important feature, which is a built-in requirement checker. When you install one of the application templates discussed in Chapter 1, Getting Started, you get a script named requirements.
It's very useful, so make a copy and place it into the web subfolder. You can download this ile from the Yii 2 repository at https: After you get the ile, you can run it from the command line by calling the following: An introduction to Yii conventions A really high-level explanation of things is as follows.
This object uses Yii's interpretation the of Model View Controller MVC composite pattern to process the request and display the result back to the sender. If you forgot or were unaware of the MVC before, then you probably want to read at least the oficial documentation for Yii for an in-depth explanation. Depending on the interpretations, a model is either what the controller uses to get data to put into a view or actually is what the controller puts into a view.
Yii 2 does not enforce any approach, but its implementation of models assumes that the model is a container for some data, either transient in-memory only or persistent with the support of the active record pattern. So, a request passes through the following steps: The web server receives the request and passes it to the index. A Yii Application object is created. It decides which Controller class should be used to handle this request. A Controller object is created.
It decides what Action it should run they can be either methods of Controller or separate classes , and run it, passing the request details there. An action is performed, and, if it were properly constructed by the programmer, it returns something rendered by the view.
It's not enforced by the framework in any way; you can have controller actions that do not render anything. A special application component is responsible for formatting data before sending it back to the user. Knowing these steps, let's modify our current entry script, so it'll render the same thing, but using the Yii framework instead of displaying a raw text output. We'll look at a nice lowchart with all the details in Chapter 12, Route Management.
We will start by introducing Yii 2 from the entry point script. At a reasonable minimum, the index. At 2 in the code, we get the coniguration tree for the application. Yii application conig is a massive PHP array describing the initial values of attributes of the application itself as well as its various components.
At 3 in the code, we make a new instance of the Application subclass representing web applications and immediately call the method called run on it. Let's make it: This is a mandatory identiier for our application. It is required because later we can split our application into different so-called modules, which we refer to using these IDs, and the top-level application obeys the same rules as a common module.
This is mandatory because it's basically the way for Yii to understand where it exists in the host ilesystem. All relative paths allowed in other settings should start from here. This is a leak from the user authentication subsystem, which we will discuss in Chapter 5, User Authentication. This setting is the private key for validating users using the remember me feature, which relies on cookies. In earlier beta versions of Yii 2, this key was generated automatically.
It was made visible by the 4e4e76e8 commit https: Apart from this setting, you can set components. This will get your application working, too. Next, we'll add some mandatory folders, because Yii just throws exceptions in case they are not there, and doesn't create them itself: These folders are used by the framework when the application is running.
Adding a controller Each controller class should have three distinct qualities: In addition, it's important to understand how Yii 2 will actually search for controller classes. Yii 2, in general, utilizes the autoloader compatible with the PSR-4 standard http: To put it simply, such an autoloader treats namespaces as paths in the ilesystem, given that there is a special root namespace deined, which maps to the root folder of the code base. Also, each class to be available through the Yii 2 autoloader has to be put into its own ile named exactly like the class itself.
So, let's create our irst controller to satisfy the smoke test. The most basic and straightforward way to deine controller actions is to deine them as public methods of the controllers having the name preixed by action.
To get into the SiteController. So, we have our smoke test passing with the Yii-based routing. Let's add some helpers for ease of debugging. Handling possible errors You can get a lot of strange errors at this stage of development.
Let's look at the ways you can use to set up your application quickly and gather as much feedback as possible. First of all, when you make a really dire mistake, such as not deining id or basePath in the application conig, you basically get a blank page as a response from the Yii application.
The only place you can look at is the logs of your web server. Of course, any other application error will end there, regardless of whether it was rendered in the browser. It's extremely important to deine it before you require the Yii library, because the Yii library will deine it in the event that you don't deine it yourself.
That's it. Here's how you do it: Lastly, you can add a custom logger to your application, which will log the errors happening within the application to a ile. Chapter 8, Overall Behavior, explains this in great detail.
Making the data and application layers Now, let's get started on the real work. To satisfy our end-to-end test, we can start from many different levels of our application. But as we already know we will work with Yii, let's igure out what we should do in the controller. We need to provide two routes: Here is the controller declaration we need for them: We need to provide the method named actionIndex to enable this route. Our intention is to provide a list of customers recorded in the database.
If this parameter is set, we ilter the customer list. Otherwise, we display all customers from the database. Here is the high-level representation of the actionIndex method: There are a lot of places where you should pass associative arrays to some functions, and the variables will have the same names as the keys of these arrays.
If you did not know about this function already, we suggest that you consult the PHP function reference and learn about it. Now we just need to igure out getRecordsAccordingToQuery. To get to this, we need to have our database irst. But before that, let's settle on the customer aggregate deinition. Deining the customer model at the data layer Why do we need the customer domain model separate from the handy ORM at all?
For a simple reason: Some parts of the customer domain model will be stuffed into a single database table. Some parts will be separated out to different tables, and maybe there'll be some additional tables to represent many-to-many relations.
More than that, we deinitely don't want the ORM details to leak to the layer where the controller is, because the very moment we do this, we'll bind ourselves to this ORM forever with no chance to replace it with anything modern.
A customer model is just a data holder class for now , so it doesn't need any tests for it. Here's how we'll deine it: We imagined one additional domain object: Here's how it is deined: To create a Customer object, we must provide the name and birthdate, but apart from that, all ields are public, so anyone can do anything with the aggregate.
Now let's think about how we'll store this model in the database. As we certainly don't want to set up this database schema manually on each deploy, we need some kind of automated way of doing this.
Yii supports the concept of migrations exactly for this purpose. But to be able to use it, we need two things. First, we need our own version of the console runner from Yii. With this, we'll be able to make our own console commands to automate things, but for now, all we need is the built-in migrate command. The script named yii should be placed in the root of the code base with the following content in it: You can see both the differences and similarities with index.
Don't forget to make this ile executable! Let's make it as follows: That's where our database is being introduced at last. Settings for the db component are in a separate coniguration snippet because we'll use exactly the same settings for our web application.
Here's how the db. A database with that name should also exist in MySQL at this time. Having all these three elements in place: To keep it short, a Yii-style migration script is a class with two methods: In the up method, you describe the change you want to make in the database.
In the down method, you describe how to revert the changes in the up method or specify by returning false that you give up; it's impossible, and you cannot revert from this particular migration. With the migration scripts, you can just add the line yii migrate to your deploy script and can be sure that all changes you want to be done in the database will be there.
Here's the content of the up method, which we set up for the customer table: We wrote so much of the untested code already that it's giving me chills.
Don't forget to actually run these migrations you just created by this command: A developer declares the class of objects corresponding to the tables so, you have one active record class deinition per table , and then you have quite a lot of functionality already done for him. Yii implementation of this pattern helps to: Let's begin with the customer table. As we already have the customer name reserved for the domain model, we'll name the active record CustomerRecord, which is logical.
Well, honestly, that's all you need to deine right now. If you worked with Yii 1. We're lacking the validation rules, though. As we already have our database schema deined and loaded, nothing stops us from deining some validation rules: Right now, it's suficient to know that this rule means that we can assign anything to this ield. By default, if an attribute is not constrained by some validation rule and not marked as safe by the safe rule, it'll be ignored by this method.
You can read the full list of built-in validators in the Yii documentation: The PhoneRecord class is a lot simpler: Later, we'll probably invent our own validator for this. The CustomerRecord. Now, we've done everything related to the database preparation. Let's use it. Decoupling from ORM We need two pieces of functionality to satisfy our end-to-end test: Get the customer record from the database that has the given phone number.
Store a new customer record in the database. We don't even need to fetch the full list of customers, because we don't check it. As we have our tiny domain model layer consisting of the Customer and Phone models, it would be wise to keep it isolated from the framework, so we need a translation layer between ORM from Yii 2 and the domain models. However, it would take a lot of pages to describe a proper setup of the repository pattern, and it's not really one of the topics of this book.
In real-world, large-scale applications, you will surely need a proper translation layer for three reasons: At some point, you'll want to replace your usage of active records in some places to something at a lower level, such as Yii DAO https: Without the repository, it's possible that your only option will be full text search for names of your ActiveRecord-based classes through the whole code base.
Again, to make this change you'll need to do a lot of changes in various places. Without the decoupling from the framework, at least its most invasive part, which is the database access layer, you'll get almost no possibility to upgrade. To not bloat this chapter too much, let's make the following methods in CustomersController. The irst one is the method to store the customer model in the database as follows: Note that the new instance of CustomerRecord magically gets the id ield value after it was saved by the save method.
The following is the method to convert from ActiveRecord instances to Customer: This method needs to be changed when there'll be a need to support several phones per customer. These two methods are essentially the translation layer between Yii and our domain model. Now, we will build the actual user interface and implement querying by phone number along the way. Creating the user interface With the CustomersController able to convert between domain models and active records, we move to the actual user interface pages at last.
Well, it should just render the UI for us: This code relies on the important convention of Yii describing from where the controller should get its views. Let's create it. What do we want on this page? According to our end-to-end test, there should be just the form to enter the customer information, along with their phone number and a Submit button.
Yii has a very extensive set of helpers to implement the web forms quickly and easily. The core concept behind them is the ActiveForm, which is the abstraction of the web form corresponding to some model from the Yii MVC interpretation. We initialize the ActiveForm and then use its methods to generate the HTML for ields corresponding to the model's attributes. This is the only verbatim example of the view ile in this book.
We won't present the use clauses and documentation blocks again to save space. The method called errorSummary is a nice shorthand, which will show all validation errors from the models in question in the event that the input is invalid according to the declared validation rules.
This is done using the special mechanism of passing data to View from Controller via the second argument of the render method. Basically, we at least need the following in the actionAdd method for the form to get correctly rendered: Routing Default routing in Yii looks like this: You need to add the following to the components section of your application coniguration: For your web application to be able to parse such URLs, you should conigure the corresponding URL rewriting in your web server.
For example, Yii developers routinely hack Apache with the following lines in the. With rewriting a set correctly, you'll be able to use URLs such as http: This is, of course, the best way to do it. For now, it's enough to know that by default, when you do render in the controller, it assumes that the view you're rendering is just a snippet wrapped by a particular script called the layout.
Apart from that, layout is just another view script. It's expected that you have some parts of the web application UI common to all pages, and a layout is exactly the place to hold them.
- FEVER MAYA BANKS FREE EBOOK DOWNLOAD
- MERCY THOMPSON EPUB DOWNLOAD
- CONCEPT OF PHYSICS FREE EBOOK DOWNLOAD
- DESIGN WITH NATURE EBOOK DOWNLOAD
- SHADES OF GREY GEHEIMES VERLANGEN EBOOK DOWNLOAD
- ROBBINS PATHOLOGIC BASIS OF DISEASE EBOOK FREE DOWNLOAD
- DUNE HERBERT EPUB DOWNLOAD
- MICROSOFT VISUAL BASIC 6.0 EBOOK FREE DOWNLOAD