首页 > 代码库 > 教程 1:让我们通过例子来学习(Tutorial 1: Let’s learn by example)
教程 1:让我们通过例子来学习(Tutorial 1: Let’s learn by example)
通过这第一个教程,我们将引导您从基础完成创建简单的带有注册表单的应用。 我们也将解释框架行为的基本方面。如果您对Phalcon的自动代码生成工具有兴趣, 您可以查看developer tools。
确认安装(Checking your installation)?
We’ll assume you have Phalcon installed already. Check your phpinfo() output for a section referencing “Phalcon” or execute the code snippet below:
我们假定你已经安装了Phalcon。 使用phpinfo()或使用get_loaded_extensions()函数查看加载的组件。
<?php print_r(get_loaded_extensions());?>
The Phalcon extension should appear as part of the output:
下面显示了phalcon已经成功加载了:
Array
(
[0] => Core
[1] => libxml
[2] => filter
[3] => SPL
[4] => standard
[5] => phalcon
[6] => pdo_mysql
)
创建项目(Creating a project)?
The best way to use this guide is to follow each step in turn. You can get the complete codehere.
使用这个教程最好的方法即是一步步的按着教程做一遍。参考手册里的例子都可以下载到。
文件结构(File structure)?
Phalcon does not impose a particular file structure for application development. Due to the fact that it is loosely coupled, you can implement Phalcon powered applications with a file structure you are most comfortable using.
Phalcon不强制使用特写的文件结构。你可以使用任何你喜欢的方式组织文件。
For the purposes of this tutorial and as a starting point, we suggest the following structure:
这里我们建议如下的文件结构:
tutorial/
app/
controllers/
models/
views/
public/
css/
img/
js/
Note that you don’t need any “library” directory related to Phalcon. The framework is available in memory, ready for you to use.
注意:我们不必须创建library目录。phalcon框架本身已经在内存中了,随时可以使用。
优美的 URL(Beautiful URLs)?
We’ll use pretty (friendly) URLs for this tutorial. Friendly URLs are better for SEO as well as being easy for users to remember. Phalcon supports rewrite modules provided by the most popular web servers. Making your application’s URLs friendly is not a requirement and you can just as easily develop without them.
In this example we’ll use the rewrite module for Apache. Let’s create a couple of rewrite rules in the /tutorial/.htaccess file:
这份指南里我们使用精简(SEL友好)的URL。SEO友好的URL易记忆。Phalcon支持几乎所有常用web服务器的rewrite模块。URL友好的书写方式不是必须的,可用可不用。这个例子里我们使用apache的rewrite模块。我们创建了一些rewrite规则,在应用根目录中的.htaccess中。
#/tutorial/.htaccess
<IfModulemod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
</IfModule>
All requests to the project will be rewritten to the public/ directory making it the document root. This step ensures that the internal project folders remain hidden from public viewing and thus eliminates security threats of this kind.
The second set of rules will check if the requested file exists and, if it does, it doesn’t have to be rewritten by the web server module:
所有的请求都被重写到了public/文件夹中,public/即是文档根目录。这样做可以使项目目录保持隐藏减少安装隐患。第二组重写规则:如果请求的文件不存在则使用web服务器重写规则。
#/tutorial/public/.htaccess
<IfModulemod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>
引导程序(Bootstrap)?
The first file you need to create is the bootstrap file. This file is very important; since it serves as the base of your application, giving you control of all aspects of it. In this file you can implement initialization of components as well as application behavior.
The tutorial/public/index.php file should look like:
首先我们要创建一个启动文件。这个文件非常重要,是整个应用的基础,可以在这个文件中对框架的各种参数行为等进行配置。在启动文件中我们可以进行组件的初始化也可以进行行为的初始化等。启动文件如下所示(可以是这个样子):
<?php
try {
//Register an autoloader注册自动加载器
$loader =new \Phalcon\Loader();
$loader->registerDirs(array(
‘../app/controllers/‘,
‘../app/models/‘
))->register();
//Create a DI创建DI
$di =new Phalcon\DI\FactoryDefault();
//Setup the view component设置视图组件
$di->set(‘view‘,function(){
$view =new \Phalcon\Mvc\View();
$view->setViewsDir(‘../app/views/‘);
return$view;
});
//Setup a base URI so that all generated URIs include the "tutorial" folder设置基础URI 这个常用来生成其它的uri
$di->set(‘url‘,function(){
$url =new \Phalcon\Mvc\Url();
$url->setBaseUri(‘/tutorial/‘);
return$url;
});
//Handle the request处理请求
$application =new \Phalcon\Mvc\Application($di);
echo$application->handle()->getContent();
} catch(\Phalcon\Exception$e) {
echo"PhalconException: ",$e->getMessage();
}
自动加载(Autoloaders)?
The first part that we find in the bootstrap is registering an autoloader. This will be used to load classes as controllers and models in the application. For example we may register one or more directories of controllers increasing the flexibility of the application. In our example we have used the component Phalcon\Loader.
With it, we can load classes using various strategies but for this example we have chosen to locate classes based on predefined directories:
启动文件中的每部分中我们注册了一个自动加载器。这个组件常用来加载控制器和模型等。例如我们可能注册一个或多个控制器目录用来提升程序的可灵活性。在这个例子中我们使用了\Phalcon\Loader.使用autoloader我们可使用许多种方式定位到类不过这里我们使用的是注册文件夹的方式(这种方式的性能是最差的在真实的项目中我们一般采用namespace或是文件夹前缀的方式):
<?php
$loader =new \Phalcon\Loader();
$loader->registerDirs(
array(
‘../app/controllers/‘,
‘../app/models/‘
)
)->register();
依赖管理(Dependency Management)?
A very important concept that must be understood when working with Phalcon is itsdependency injection container. It may sound complex but is actually very simple and practical.
A service container is a bag where we globally store the services that our application will use to function. Each time the framework requires a component, it will ask the container using an agreed upon name for the service. Since Phalcon is a highly decoupled framework, Phalcon\DI acts as glue facilitating the integration of the different components achieving their work together in a transparent manner.
我们中使用Phalcon时会一定要理解一个非常重要的概念即是其依赖注入容器。这听起来非常的复杂其实非常简单。依赖容器即是一个存放了所有全局服务(组件)的空间(容器也可说是工具箱)。每次框架需要使用一个组件时它都会以注册的名字从容器取要想要的组件(工具)。因为Phalcon本身是松耦合的,\Phalcon\DI在其中扮演了一个联接所有组件的纽带(当然这对使用者来说是透明的)。
<?php
//Create a DI
$di =new Phalcon\DI\FactoryDefault();
Phalcon\DI\FactoryDefault is a variant of Phalcon\DI. To make things easier, it has registered most of the components that come with Phalcon. Thus we should not register them one by one. Later there will be no problem in replacing a factory service.
In the next part, we register the “view” service indicating the directory where the framework will find the views files. As the views do not correspond to classes, they cannot be charged with an autoloader.
Services can be registered in several ways, but for our tutorial we’ll use ananonymous function:
\Phalcon\DI\FactoryDefault是\Phalcon\DI的一个变体。为了使我们的开发更简单,FactoryDefault在初始化时注册了许多组件。因此我们在开发中无须再一个个的注册了。不过在稍后的开发中我们依然可以替换这些自动注册的组件。接下来的部分我们了view服务,它指明了框架要去哪一个文件中找视图文件。由于视图文件里一般都是html文件即非php类所以不能使用Autoloader进行加载. 中Phalcon中我们可以使用多种方式注册服务,不过这里我们使用的是匿名函数(而且我们推荐这样做)。
<?php
//Setup the view component
$di->set(‘view‘,function(){
$view =new \Phalcon\Mvc\View();
$view->setViewsDir(‘../app/views/‘);
return$view;
});
Next we register a base URI so that all URIs generated by Phalcon include the “tutorial” folder we setup earlier. This will become important later on in this tutorial when we use the classPhalcon\Tag to generate a hyperlink.
接下来我们注册了一个基URI,这样以后所有使用Phalcon组件所自动生成的URI里就会包含我们之前定义的”tutourial”文件夹了。这在以后我们使用\Phalcon\Tag生成URI时是非常重要的。
<?php
//Setup a base URI so that all generated URIs include the "tutorial" folder
$di->set(‘url‘,function(){
$url =new \Phalcon\Mvc\Url();
$url->setBaseUri(‘/tutorial/‘);
return$url;
});
In the last part of this file, we find Phalcon\Mvc\Application. Its purpose is to initialize the request environment, route the incoming request, and then dispatch any discovered actions; it aggregates any responses and returns them when the process is complete.
在文件的最后有\Phalcon\Mvc\Application. 它的主要作用即是初始化请求环境,路同请求,然后分发action,最后在处理结束时收集处理的结果然后返回给客户端(浏览器)。
<?php
$application =new \Phalcon\Mvc\Application($di);
echo$application->handle()->getContent();
As you can see, the bootstrap file is very short and we do not need to include any additional files. We have set ourselves a flexible MVC application in less than 30 lines of code.
上面我们已经看了,我们Phalcon的启动文件非常小,我们没有包含进来任何的文件。我们只使用了30行左右的代码即生成了一个易扩展的mvc框架。
创建控制器(Creating a Controller)?
By default Phalcon will look for a controller named “Index”. It is the starting point when no controller or action has been passed in the request. The index controller (app/controllers/IndexController.php) looks like:
默认情况下,Phalcon会查找一个名为Index的控制器,当未批定控制器和action时。Index控制器通常如下:
<?php
class IndexControllerextends \Phalcon\Mvc\Controller
{
publicfunctionindexAction()
{
echo"<h1>Hello!</h1>";
}
}
The controller classes must have the suffix “Controller” and controller actions must have the suffix “Action”. If you access the application from your browser, you should see something like this:
控制器类必须以Controller结尾,action必须以Action结尾。如果我们通过控制器访问应用,会显示如下:
Congratulations, you’re flying with Phalcon!
恭喜,Phalcon已经正常运行了!
输出到视图(Sending output to a view)?
Sending output to the screen from the controller is at times necessary but not desirable as most purists in the MVC community will attest. Everything must be passed to the view that is responsible for outputting data on screen. Phalcon will look for a view with the same name as the last executed action inside a directory named as the last executed controller. In our case (app/views/index/index.phtml):
输出结果到前台显示很多时候需要显示出来但并不是必须的。所有要显示的数据必须发送到视图然后才能显示。Phalcon会查找和最后请示同名的视图文件。在我们这个例子中即是(app/views/index/index.phtml)。
<?phpecho"<h1>Hello!</h1>";
Our controller (app/controllers/IndexController.php) now has an empty action definition:
我们的控制器(app/controllers/IndexController.php)里放一个空的action:
<?php
class IndexControllerextends \Phalcon\Mvc\Controller
{
publicfunctionindexAction()
{
}
}
The browser output should remain the same. ThePhalcon\Mvc\View static component is automatically created when the action execution has ended. Learn more aboutviews usage here .
这样浏览器依然会保持原样输出。\Phalcon\Mvc\View静态组件会在action执行结束时自动创建。
设计注册表单(Designing a sign up form)?
Now we will change the index.phtml view file, to add a link to a new controller named “signup”. The goal is to allow users to sign up within our application.
现在我们来修改index.phtml文件,并添加一个名为signup的链接。我们做这个主要是想让用户签入。
<?php
echo"<h1>Hello!</h1>";
echo Phalcon\Tag::linkTo("signup","Sign Up Here!");
The generated HTML code displays an anchor (“a”) HTML tag linking to a new controller:
以上代码生成的内容中的锚连接到一个新的控制器如下:
<h1>Hello!</h1><ahref=http://www.mamicode.com/"/tutorial/signup">Sign Up Here!</a>
To generate the tag we use the class Phalcon\Tag. This is a utility class that allows us to build HTML tags with framework conventions in mind. A more detailed article regarding HTML generation can befound here
这里我们使用\Phalcon\Tag来生成标签。这个工具类可以生成常用的html标签。更详尽的生成html的方法可以看这篇文章。
Here is the Signup controller (app/controllers/SignupController.php):
这里是Signup控制器(app/controllers/SignupController.php)
<?php
class SignupControllerextends \Phalcon\Mvc\Controller
{
publicfunctionindexAction()
{
}
}
The empty index action gives the clean pass to a view with the form definition (app/views/signup/index.phtml):
这个空的action未传送任何参数到视图中的form定义中:
<?phpuse Phalcon\Tag;?>
<h2>Sign up using this form</h2>
<?phpecho Tag::form("signup/register");?>
<p>
<labelfor="name">Name</label>
<?phpecho Tag::textField("name")?>
</p>
<p>
<labelfor="email">E-Mail</label>
<?phpecho Tag::textField("email")?>
</p>
<p>
<?phpecho Tag::submitButton("Register")?>
</p>
</form>
Viewing the form in your browser will show something like this:
视图最终在浏览器会显示如下:
Phalcon\Tag also provides useful methods to build form elements.
The Phalcon\Tag::form method receives only one parameter for instance, a relative uri to a controller/action in the application.
By clicking the “Send” button, you will notice an exception thrown from the framework, indicating that we are missing the “register” action in the controller “signup”. Our public/index.php file throws this exception:
\Phalcon\Tag也提供了一个非常有用的方法用以生成表单元素。\Phalcon\Tag:form方法仅有一个参数: 相对的controller/action uri.当我们点击Send按钮时,会显示一个异常信息:我们的Signup控制器中无register方法。public/index.php会抛出如下异常:
PhalconException: Action “register” was not found on controller “signup”
Implementing that method will remove the exception:
添加indexAction会去除掉这个异常信息:
<?php
class SignupControllerextends \Phalcon\Mvc\Controller
{
publicfunctionindexAction()
{
}
publicfunctionregisterAction()
{
}
}
If you click the “Send” button again, you will see a blank page. The name and email input provided by the user should be stored in a database. According to MVC guidelines, database interactions must be done through models so as to ensure clean object-oriented code.
如果再次点击Send按钮,会显示一个空的页面。用户输入的名称和email应该保存到数据库中。根据MVC设计模式,数据库交互最好在模型中实现,这样才能保证代码的整洁。
创建模型(Creating a Model)?
Phalcon brings the first ORM for PHP entirely written in C-language. Instead of increasing the complexity of development, it simplifies it.
Before creating our first model, we need to create a database table outside of Phalcon to map it to. A simple table to store registered users can be defined like this:
Phalcon中的ORM是第一个完全由C实现的ORM。Phalcon中的ORM并一复杂,反而非常简单。在我们创建模型之前我们必须要创建一个新的数据库表,可以才可以使模型和数据库表映射反过来说二者是一一对应的。下面我们创建了一个简单的存储用户信息的表:
CREATETABLE `users` (
`id` int(10) unsignedNOTNULL AUTO_INCREMENT,
`name` varchar(70)NOTNULL,
`email` varchar(70)NOTNULL,
PRIMARYKEY (`id`)
);
A model should be located in the app/models directory (app/models/Users.php). The model maps to the “users” table:
模型应该放在app/models文件夹中(app/modesl/User.php) 。这个模型映射到了users表格中:
<?php
class Usersextends \Phalcon\Mvc\Model
{
}
设置数据库连接(Setting a Database Connection)?
In order to be able to use a database connection and subsequently access data through our models, we need to specify it in our bootstrap process. A database connection is just another service that our application has that can be used for several components:
为了使用数据库,我们必须在启动文件中设置连接信息。数据库连接是我们注册的另一个服务,可以被多个组件使用:
<?php
try {
//Register an autoloader
$loader =new \Phalcon\Loader();
$loader->registerDirs(array(
‘../app/controllers/‘,
‘../app/models/‘
))->register();
//Create a DI
$di =new Phalcon\DI\FactoryDefault();
//Setup the database service
$di->set(‘db‘,function(){
returnnew \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" =>"localhost",
"username" =>"root",
"password" =>"secret",
"dbname" =>"test_db"
));
});
//Setup the view component
$di->set(‘view‘,function(){
$view =new \Phalcon\Mvc\View();
$view->setViewsDir(‘../app/views/‘);
return$view;
});
//Setup a base URI so that all generated URIs include the "tutorial" folder
$di->set(‘url‘,function(){
$url =new \Phalcon\Mvc\Url();
$url->setBaseUri(‘/tutorial/‘);
return$url;
});
//Handle the request
$application =new \Phalcon\Mvc\Application($di);
echo$application->handle()->getContent();
} catch(Exception$e) {
echo"PhalconException: ",$e->getMessage();
}
With the correct database parameters, our models are ready to work and interact with the rest of the application.
数据库连接配置正确了,模型即可以使用了,也可以和应用的其它部分进行交互了。
使用模型保存数据(Storing data using models)?
Receiving data from the form and storing them in the table is the next step.
下一步中我们从表单中接收了数据然后保存在了数据库的表中
<?php
class SignupControllerextends \Phalcon\Mvc\Controller
{
publicfunctionindexAction()
{
}
publicfunctionregisterAction()
{
$user =new Users();
//Store and check for errors//错误检查与保存
$success =$user->save($this->request->getPost(),array(‘name‘,‘email‘));
if ($success) {
echo"Thanks for registering!";
} else {
echo"Sorry, the following problems were generated: ";
foreach ($user->getMessages()as$message) {
echo$message->getMessage(),"<br/>";
}
}
$this->view->disable();
}
}
We then instantiate the Users class, which corresponds to a User record. The class public properties map to the fields of the record in the users table. Setting the relevant values in the new record and calling save() will store the data in the database for that record. The save() method returns a boolean value which indicates whether the storing of the data was successful or not.
The ORM automatically escapes the input preventing SQL injections so we only need to pass the request to the save method.
Additional validation happens automatically on fields that are defined as not null (required). If we don’t enter any of the required fields in the sign up form our screen will look like this:
这里我们实例化了Users类,它对应了一条User表中的记录。这个类的公共属性映射到用户表中的字段。设置对应的值到新实例中然后调用保存方法即可保存数据到数据库中。save()方法会返回一个boolean值指示了是否正确保存了数据。ORM会自动为我们免除sql 注入的危险,所以我们只需设置值即可。非空字段(必须字段)的验证会自动进行。如果非空字段的值未填写则会出现如下错误:
结束语(Conclusion)?
This is a very simple tutorial and as you can see, it’s easy to start building an application using Phalcon. The fact that Phalcon is an extension on your web server has not interfered with the ease of development or features available. We invite you to continue reading the manual so that you can discover additional features offered by Phalcon!
上面这个例子极其简单,由此不难看出使用Phalcon做开发是如此的容易。Phalcon以C扩展实现的框架方式没有对易开发性有任何影响,依然非常容易使用,而且功能也未受到任何影响。我们推荐您接着阅读后面的手册这样可以发现Phalcon的更多功能。
一些应用(Sample Applications)?
The following Phalcon-powered applications are also available, providing more complete examples:
下面的一些更复杂的例子也是使用Phalcon开发的:
?INVO application: Invoice generation application. Allows for management of products, companies, product types. etc.
INVO应用:订单生成。允许用户管理产品,公司,产品类型等。
?PHP Alternative website: Multilingual and advanced routing application
PHP镜像站点:多语言与高级路由应用。
?Album O’Rama: A showcase of music albums, handling big sets of data with PHQL and usingVolt as template engine
O’Rama唱片:一个唱片展示应用,使用PHQL处理数据,使用Volt作为模板引擎。
?Phosphorum: A simple and clean forum
一个简单清爽的论坛
教程 1:让我们通过例子来学习(Tutorial 1: Let’s learn by example)