Beginner of Lithium Framework: Key Points
Lithium is a simple and efficient PHP framework suitable for PHP 5.3 and above. It is designed to provide a good set of tools to launch your web application without being too restrictive.
Lithium uses the model-view-controller (MVC) architecture, which will be discussed in this article. I'll show you how it works and how to define some business and representation logic for your application using this framework. We will perform the following steps:
We will set up a controller to route URL requests. This controller will use the data model to obtain and process some information from the database. This information will then be displayed in the browser using the view. All of this is a standard MVC process, but it is a pleasure to execute in Lithium.
I assume you have the framework set up on the server, at least you can see the launch page of the default application when you navigate to the URL. In addition, you need a database with some information. I'll use MySQL, but Lithium supports many other storage systems like MongoDB or CouchDB.
If you want to continue learning, I have set up a Git repository and you can clone it. The master branch contains the normal Lithium framework, while the MVC branch contains the code for this article. Don't forget to initialize and update the lithium submodule. To connect to your database, copy the connections_default.php file located in the app/config/bootstrap folder and rename it to connections.php. Then add your credentials to the file.
Let's get started.
Data
Before entering interesting MVC content, let's add a table in the database with some information. I'll use virtual page data, so my table (named pages) will contain an id column (INT, auto-increment and primary key), a title column (varchar 255), a content column (text) and a created column (INT ). In this table, I have two rows of sample data. If you want to follow the steps exactly, here are the table creation statements:
CREATE TABLE `pages` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `content` text, `created` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
The following is my virtual data line:
INSERT INTO `pages` (`id`, `title`, `content`, `created`) VALUES (1, 'My awesome page title', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 1397158745), (2, 'Some other page title', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 1397158768);
Of course, you can use other data.
C stands for controller
Controllers are probably the most important part of any MVC framework. Their purpose is to handle requests routed by the application routing system.
If you look at the app/controllers/ folder of the app, you will find that this is where we have to place the controller. Let's create a new file there called SiteController.php (each controller class is in its own file) and paste the following class declaration to start:
<?php namespace app\controllers; class SiteController extends \lithium\action\Controller { }
As you can see, we extend the Lithium base controller class to our own class called SiteController. In this class, you can create methods that execute the required logic when requesting from a URL. We'll see how it actually applies later, but first, let's understand how routing works.
By default, when constructing the URL, we use parameters that map to the controller class name (in this case site), method, and parameters. If the method name is not passed, Lithium will assume a method named index() on its own. So if you navigate to http://example.com/site/, Lithium will look for this method and call it. Now suppose we have a method called view() which takes a parameter ($id). The URL that calls the controller method is http://example.com/site/view/1, where view is the name of the method and 1 is the parameter passed to the function. If the method gets more parameters, you just separate them with slashes (/) in the URL.
However, as I mentioned, this is the default behavior. For more control, you can define your own route in the /app/config/routes.php file. I won't go into details, but you can find more information on the corresponding documentation page.
Now let's go ahead and create a page() method that will be responsible for displaying individual pages from my virtual database:
public function page() { // 模拟页面信息。 $title = 'My awesome page title'; $content = 'My awesome page content. Yes indeed.'; $created = '10 April 2014'; // 准备页面信息以传递给视图。 $data = array( 'title' => $title, 'content' => $content, 'created' => $created, ); // 将数据传递给视图。 $this->set($data); }
Above, we simulate the database page information and store it in an array. We then pass this array to the controller's set() method (which we inherited) and then send it to the view. Alternatively, we can return the $data array, instead of using the set() method. But in both cases, the keys of the array represent variable names, which we can then access from the view file. Let's see how it works.
(The following content is similar to the original text, but the statement has been adjusted and rewritten, maintaining the original intention, and avoiding duplicate code blocks)
V stands for view
View is the presentation layer of the MVC framework. They are used to separate the business logic of an application from the representation and allow easy thematic of content displayed in the browser.
Let's create a view to display our page information. In the app/views/ folder, you need to create another folder named after the controller class that uses it (in this case site). In this folder, you have to create a file named after the method itself, with the .html.php extension attached. This is the convention Lithium names views, which allows us to easily connect them to the controller.
So for our page example, the new file will be located in app/views/site/page.html.php.
In this file, paste the following:
CREATE TABLE `pages` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `content` text, `created` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
As you might have guessed, here are some basic tags where we will print variables named for passing array keys from the controller. Lithium uses this syntax to print variables, as it also runs them through its $h() function, which is responsible for cleaning up HTML. But this only applies to print variables, not properties of $this object.
To test what we have done so far, navigate to http://example.com/site/page and you should see a nice page showing the simulation information. You will also notice that our simple view is rendered in more complex layouts (the default layout that comes with the framework).
Layouts in Lithium are used to wrap content using commonly used tags such as titles and footers. They are located in the app/layouts folder where they render the view using $this->content(). Our view is rendered by default in the default.html.php layout, but you can specify another layout as you want. You can do this from the controller that renders the view, either as a class attribute applied to all methods of that controller, or in the method itself, like so:
INSERT INTO `pages` (`id`, `title`, `content`, `created`) VALUES (1, 'My awesome page title', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 1397158745), (2, 'Some other page title', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 1397158768);
We will stick to the default layout because it looks good for our demo purposes.
M stands for model
Now that the request and representation logic has been processed, it is time to replace the simulated page data with our virtual database content. We will use models to abstract and easily access this information.
Model classes are a very important part of the MVC framework because they define and process content in the database. They also enable applications to easily perform CRUD (create, read, update, delete) operations on this data. Let's see how they work in Lithium.
The first thing you need to do is create a class file called Pages.php in the app/models folder and paste the following in it:
<?php namespace app\controllers; class SiteController extends \lithium\action\Controller { }
We just extended the base model class and used all its methods. Our model class name must match the database table containing the relevant records. So if yours is not pages, make sure to adjust accordingly, as Lithium will automatically get this naming to simplify our work.
Next, we need to include this file in our controller class file, so please paste the following below the namespace declaration:
CREATE TABLE `pages` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `content` text, `created` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
The next is to delete the mock content in the page() method and make sure this function passes a $id parameter so that we know which page we need to retrieve. Our simple task left is to query the page record and pass the results to the view. Therefore, the modified page() method will look like this:
INSERT INTO `pages` (`id`, `title`, `content`, `created`) VALUES (1, 'My awesome page title', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 1397158745), (2, 'Some other page title', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 1397158768);
We use the first() method of the model parent class to query using conditions. The result is an object from which we use the data() method to retrieve the record data. This data takes an array with the name of the table column as the key. The rest is the same as before, except that we format the created field using the PHP date() function because what we get from the database is the UNIX timestamp. That's it.
If we navigate to http:example.com/site/page/1, we should see a page with ID 1. If we switch the last URL parameter to 2, the page should load the second record. tidy.
Conclusion
In this tutorial, we saw how easy it is to understand and use the Lithium MVC framework. We learned how to define controllers, views, and models, and how to use them together to create a neat and separate application flow. We also saw how useful the Lithium agreement was for us to get started. Even if we don't realize it, we abstract our database content and expose it for easy access.
I hope you have learned something and are curious about delving deeper into other powerful features that Lithium offers. What are some built-in CRUD methods? How to expand them? How to define your own custom routes? How to use multiple layouts to render smaller elements even in view? These are the powerful features Lithium offers for our web applications and are worth a try.
Did I arouse your curiosity? Want to learn more about this excellent framework?
(The FAQ part is the same as the original text, no modification is required)
The above is the detailed content of Lithium Framework: Getting Started. For more information, please follow other related articles on the PHP Chinese website!