框架入门_锂框架:入门

框架入门

Lithium is a lean but mean PHP framework (machine?) built for PHP 5.3 and up. It is designed to provide a good toolset for starting your web application, but one that is not too confining.

Lithium是一个精简但卑鄙PHP框架(机器?),用于PHP 5.3及更高版本。 它旨在为启动Web应用程序提供一个很好的工具集,但它并不太局限。

Lithium uses the Model-View-Controller(MVC) architecture and this is what we are going to look at in this article. I will show you how it works and how you can define some of your application’s business and presentation logic using this framework. There are a few things we will do in this respect.

Lithium使用Model-View-Controller(MVC)架构,这就是我们将在本文中介绍的内容。 我将向您展示其工作原理,以及如何使用此框架定义应用程序的某些业务和表示逻辑。 我们将在这方面做一些事情。

We will set up a Controller to route URL requests to. This Controller will get and process some information from the database with the help of a data Model. This information will then be displayed in the browser using a View. All standard MVC stuff, but a real pleasure to perform with Lithium.

我们将设置一个Controller来将URL请求路由到。 该控制器将在数据模型的帮助下从数据库获取并处理一些信息。 然后,将使用“视图”在浏览器中显示此信息。 所有标准的MVC素材,但是与Lithium一起演奏确实很高兴。

I will assume you already have the framework set up on your server to the point that you can at least see the default app starting page if you navigate to the URL. Additionally, you’ll need a database populated with some information. I’ll use MySQL but Lithium supports a number of other storage systems like MongoDB or CouchDB.

我将假定您已经在服务器上设置了框架,以至于如果您导航到URL,则至少可以看到默认的应用程序起始页。 此外,您将需要一个包含一些信息的数据库。 我将使用MySQL,但Lithium支持许多其他存储系统,例如MongoDB或CouchDB。

I have set up a Git repository that you can clone if you want to follow along. The master branch contains the vanilla Lithium framework whereas the MVC branch contains the code from this article. Don’t forget to also init and update the lithium submodule. To connect your database, make a copy of the connections_default.php file located in the app/config/bootstrap folder and rename it connections.php. Then add your credentials inside that file.

我已经建立了一个Git存储库 ,如果您想继续的话可以克隆它。 master分支包含普通的Lithium框架,而MVC分支包含本文的代码。 别忘了还要initupdate锂子模块。 要连接数据库,请复制位于app/config/bootstrap文件夹中的connections_default.php文件的副本,并将其重命名为connections.php 。 然后将您的凭据添加到该文件中。

Let’s begin.

让我们开始。

数据 (The data)

Before getting into the fun MVC stuff, let’s get a table into our database with some information. I will be working with dummy page data so my table (called 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). And in this table I have 2 sample rows. If you want to follow along exactly, here is the table create statement:

在介绍有趣的MVC东西之前,让我们在数据库中获取一些信息表。 我将使用伪页面数据,因此我的表(称为pages )将包含一个id列(INT,自动递增和主键),一个title列(varchar 255),一个content列(文本)和一个created列(INT )。 在此表中,我有2个示例行。 如果要严格遵循,请参见表create语句:

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;

And here are my dummy rows:

这是我的虚拟行:

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 something else.

当然,您可以使用其他东西。

C代表控制器 (C stands for Controller)

Controllers are probably the most important part of any MVC framework. Their role is to process requests routed to it by the application’s routing system.

控制器可能是任何MVC框架中最重要的部分。 它们的作用是处理由应用程序的路由系统路由到该请求的请求。

If you look in the app/controllers/ folder of your application you’ll see that this is where we have to put ours. Let’s create there a new file called SiteController.php (each Controller class resides in its own file) and paste in the following class declaration to get started:

如果您查看app/controllers/文件夹,您会发现这是我们必须放置的文件夹。 让我们在那里创建一个名为SiteController.php的新文件(每个Controller类驻留在其自己的文件中)并粘贴以下类声明以开始使用:

<?php

namespace app\controllers;

class SiteController extends \lithium\action\Controller {

}

As you can see we are extending the Lithium base controller class into our own called SiteController. Inside this class you create methods that perform the logic needed when they are requested from the URL. We’ll see this in action in a minute, but first, let’s understand how the routing works.

如您所见,我们将Lithium基本控制器类扩展到我们自己的称为SiteController 。 在此类内,您将创建执行从URL请求它们时所需的逻辑的方法。 我们将在一分钟内看到实际效果,但首先,让我们了解路由的工作原理。

By default, when constructing the URL, we use arguments that map to the names of the Controller class (in our case, site), methods and parameters. If no method name is passed, Lithium will assume one by itself called index(). So if you navigate to http://example.com/site/, Lithium will look for this method and call it. Now let’s say we have a method called view() that takes 1 argument ($id). The URL to call that Controller method is http://example.com/site/view/1, where view is the name of the method and 1 is the parameter that gets passed to this function. And if the method gets more parameters, you just pass them in the URL separated by slashes (/).

默认情况下,在构造URL时,我们使用的参数映射到Controller类的名称(在本例中为site ),方法和参数。 如果未传递任何方法名,则Lithium将自行采用一个名为index() 。 因此,如果您导航到http://example.com/site/将寻找并调用此方法。 现在假设我们有一个名为view()的方法,该方法带有1个参数( $id )。 调用该Controller方法的URL是http://example.com/site/view/1 ,其中view是方法的名称,而1是传递给此函数的参数。 而且,如果该方法获得更多参数,则只需将其传递到以斜杠( / )分隔的URL中即可。

However, like I mentioned, this is the default behavior. For more control, you can define routes yourself in the /app/config/routes.php file. I won’t go into details but you can find more information on the appropriate documentation page.

但是,就像我提到的,这是默认行为。 为了获得更多控制权,您可以在/app/config/routes.php文件中自己定义路由。 我不会详细介绍,但是您可以在相应的文档页面上找到更多信息。

Now let’s go ahead and create a page() method that will be in charge of displaying individual pages from my dummy database:

现在,让我们继续创建一个page()方法,该方法将负责显示虚拟数据库中的各个页面:

public function page() {

    // Mock page info.
    $title = 'My awesome page title';
    $content = 'My awesome page content. Yes indeed.';
    $created = '10 April 2014';

    // Prepare page info for passing to the View.
    $data = array(
      'title' => $title,
      'content' => $content,
      'created' => $created,
    );

    // Pass the data to the View.
    $this->set($data);

}

Above, we mock database page information and store it an array. We then pass this array to the set() method of the Controller class (that we inherit) and this gets sent on to the View. Alternatively, we can also return the $data array instead of using the set() method. But in both cases, the keys of the array represent the variable names that we can then access from our View file. Let’s see how that works.

上面,我们模拟数据库页面信息并将其存储在数组中。 然后,我们将此数组传递给Controller类(我们继承)的set()方法,然后将其发送到View。 另外,我们也可以返回$data数组而不是使用set()方法。 但是在两种情况下,数组的键都代表了变量名,然后我们可以从View文件中访问它们。 让我们看看它是如何工作的。

V代表View (V stands for View)

Views are the presentation layer of an MVC framework. They are used to keep the business logic of the application separate and to allow for an easy theming of what gets displayed to the browser.

视图是MVC框架的表示层。 它们用于使应用程序的业务逻辑分离,并允许轻松地将显示在浏览器中的内容设置为主题。

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 our case, site). Inside this folder, you have to create a file named after the method itself, appended with the .html.php extension. This is the Lithium naming convention for Views that makes it very easy for us to connect them to Controllers.

让我们创建一个视图来显示我们的页面信息。 在app/views/文件夹中,您需要创建一个使用它的Controller类命名的另一个文件夹(在我们的示例中为site )。 在此文件夹中,您必须创建一个以方法本身命名的文件,并附加.html.php扩展名。 这是View的Lithium命名约定,这使我们很容易将它们连接到Controller。

So for our page example, the new file will be at app/views/site/page.html.php.

因此,对于我们的页面示例,新文件将位于app/views/site/page.html.php

Inside this file, paste the following:

在此文件内,粘贴以下内容:

<!-- Title -->
<h1><?=$title ?></h1>

<!-- Created date -->
<p><?=$created ?></p>

<!-- Main content -->
<div class="content">
  <?=$content ?>
</div>

As you probably already guessed, this is some basic markup into which we print the variables named after the array keys passed from the Controller. Lithium uses this syntax to print variables because it also runs them through its $h() function which is responsible for sanitizing HTML. This applies however only to when you print variables and not properties of the $this object.

您可能已经猜到了,这是一些基本标记,我们在其中打印以从Controller传递的数组键命名的变量。 Lithium使用此语法来打印变量,因为它还通过负责净化HTML的$h()函数来运行它们。 但是,这仅适用于打印变量而不是$this对象的属性的情况。

To test out what we have so far, navigate to http://example.com/site/page and you should see a nice page with the mock information displayed. You’ll also notice that our simple View is rendered inside a more complex layout (the default one that comes with the framework).

要测试到目前为止的内容,请导航至http://example.com/site/page ,您应该会看到一个漂亮的页面,其中显示了模拟信息。 您还将注意到,我们的简单视图是在更复杂的布局(框架随附的默认布局)中呈现的。

Layouts in Lithium are used to wrap content with commonly used markup such as headers and footers. They live in the app/layouts folder and they use $this->content() to render the View inside. Our View is rendered by default inside the default.html.php layout but you can specify another one if you want. You do this from the Controller that renders the View, either as a class property to be applied to all methods of that Controller, or inside the method itself like this:

Lithium中的布局用于包装带有常用标记(如页眉和页脚)的内容。 它们位于app/layouts文件夹中,并使用$this->content()在内部渲染View。 默认情况下,我们的视图在default.html.php布局中呈现,但是您可以根据需要指定另一个视图。 您可以通过呈现视图的Controller来执行此操作,可以将其作为要应用于该Controller的所有方法的类属性,也可以在方法本身内部进行如下操作:

public function page() {

    // Method logic ...

    $this->_render['layout'] = 'yourLayout';   
}

We will stick to the default one because it looks nice for our demonstration purposes.

我们将坚持使用默认值,因为它对于我们的演示目的来说看起来不错。

M代表模型 (M stands for Model)

Now that the request and presentation logic are taken care of, its time to replace the mock page data with our dummy database content. We will use a Model to abstract and easily access this information.

现在已经处理了请求和表示逻辑,现在该用我们的虚拟数据库内容替换模拟页面数据了。 我们将使用模型来抽象并轻松访问此信息。

Model classes are a very important part of an MVC framework because they define and handle the content in your database. They also make it easy for the application to perform CRUD (create, read, update, delete) operations on this data. Let’s see how they work in Lithium.

模型类是MVC框架中非常重要的部分,因为它们定义和处理数据库中的内容。 它们还使应用程序可以轻松地对此数据执行CRUD(创建,读取,更新,删除)操作。 让我们看看它们如何在锂中工作。

The first thing you need to do is create a class file in the app/models folder called Pages.php and inside paste the following:

您需要做的第一件事是在app/models文件夹中创建一个名为Pages.php的类文件,并在其中粘贴以下内容:

<?php

namespace app\models;

class Pages extends \lithium\data\Model {

}

We are just extending the base Model class and making use of all its methods. The name of our Model class needs to match the database table that contains the relevant records. So if yours is not pages, make sure you adapt accordingly because Lithium will automatically pick up on this naming to make things easier for us.

我们只是扩展基础Model类,并利用其所有方法。 我们的Model类的名称需要匹配包含相关记录的数据库表。 因此,如果您的pages不是pages ,请确保进行相应调整,因为Lithium会自动选择该命名,以使我们更轻松。

Next, we need to include this file in our Controller class file, so paste the following below the namespace declaration:

接下来,我们需要将此文件包含在Controller类文件中,因此将以下内容粘贴到名称空间声明下面:

use app\models\Pages;

It follows to remove the mock content from the page() method and make sure this function gets passed an $id parameter so that we know which page we need to retrieve. And we are left with the simple task of querying for the page record and passing the results to the View. So the revised page() method will look something like this:

接下来是从page()方法中删除模拟内容,并确保此函数传递了$id参数,以便我们知道需要检索哪个页面。 我们剩下的简单任务是查询页面记录并将结果传递给View。 因此,修改后的page()方法将如下所示:

public function page($id) {

    // Look for the first record that matches the passed criteria
    $record = Pages::first(array('conditions' => array('id' => $id)));
    $page = $record->data();

    // Prepare page info for passing to the View.
    $data = array(
      'title' => $page['title'],
      'content' => $page['content'],
      'created' => date('F j Y', $page['created']),
    );

    // Pass the data to the View.
    $this->set($data);

}

We are using the first() method of the Model parent class to query using conditions. The result is an object from which we retrieve the record data using the data() method. And that is in the form of an array keyed by the name of the table columns. The rest is like before except for the created field that we format using the PHP date() function since we are getting a UNIX timestamp from the database. And that’s pretty much it.

我们使用Model父类的first()方法来查询条件。 结果是一个对象,我们使用data()方法从中检索记录数据。 这是由表列名称作为键的数组形式。 其余部分与以前一样,除了created字段需要使用PHP date()函数进行格式化外,因为我们从数据库中获取了UNIX时间戳。 就是这样。

If we navigate to http:example.com/site/page/1, we should see the page with the ID of 1. If we switch the last URL argument to 2, the page should load the second record. Neat.

如果导航到http:example.com/site/page/1 ,则应看到ID为1的页面。如果将最后一个URL参数切换为2,则该页面应加载第二条记录。 整齐。

结论 (Conclusion)

In this tutorial we’ve seen how easy it is to understand and work with the Lithium MVC framework. We’ve learned how to define Controllers, Views and Models and how to use them together to create a neatly separated application process. We’ve also seen how helpful the Lithium conventions are to get us started. Without even knowing it we abstracted our database content and exposed it for very easy access.

在本教程中,我们看到了理解和使用Lithium MVC框架很容易。 我们已经学习了如何定义控制器,视图和模型,以及如何将它们一起使用以创建一个整洁的应用程序流程。 我们还看到了锂约定对我们入门的帮助。 甚至不知道它,我们提取了数据库内容并公开了它,以便于访问。

I hope you learned something and are curious enough to go a bit more in depth and look at the other powerful features Lithium has to offer. What are some of the built in CRUD methods and how can you extend them? How can you define your own custom routes? How can you use multiple layouts and even render smaller elements within your Views? These are all great features Lithium offers us for our web application and are worth checking out.

我希望您学到了一些东西,并且好奇到足以进一步深入研究锂电所提供的其他强大功能。 内置的CRUD方法有哪些,如何扩展它们? 您如何定义自己的自定义路线? 如何使用多个布局,甚至在视图中渲染较小的elements ? 这些都是Lithium为我们的Web应用程序提供的出色功能,值得一试。

Did I make you curious? Want to read more about this great framework?

我让你好奇吗? 想更多地了解这个伟大的框架吗?

翻译自: https://www.sitepoint.com/lithium-framework-getting-started/

框架入门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值