phalcon模型中怎么写构造方法怎么写

Phalcon框架中文简陋文档
教程2:INVO简介在本次教程中,我们通过一个更加完整的应用程序来更加深入地了解Phalcon的开发。INVO是我们作为示例所创建的应用之一。INVO是一个小型网站,它允许用户开具发票以及执行比如管理他们的客户及产品等其他任务。你可以从克隆它的源代码。
此外,INVO是基于引导文件生成的客户端框架。尽管这个应用并不会(真正的)开具发票,它是作为一个示例来让我们了解框架是如何工作的。
项目结构当你在你的站点根目录克隆这个项目之后,你就会看到如下的文件结构:
123456789101112131415161718invo/
controllers/
正如之前我们所说的,Phalcon并不会强制规定应用程序的开发遵循特定的文件结构。该项目提供了一个简单的MVC结构和一个public/文件目录。
当你在你的浏览器中访问这个应用http://localhost/invo的时候你会看到如下图所示:
这个应用分为两个部分,前端部分是一个开放的部分,访客可以获取关于INVO的有关内容和联系信息。第二个部分是后端,是一个已注册用户可以管理他/她的产品及客户的管理后台。
路由INVO使用基于内置的标准路由模式。这些路由规则匹配模式是这样的:/:controller/:action/:params,它代表URI的第一个部分对应的是控制器,第二部分对应的是动作/方法, 其余的则是(动作的)参数。
下面的路由/session/register会执行到SessionController控制器以及它的registerAction动作。
配置INVO具有一个设置了该应用的默认参数的配置文件。这个文件位于app/config/config.ini,同时它在应用程序的引导文件(public/index.php) 中的第一行加载。
12345678&?phpuse Phalcon\Config\Adapter\Ini as ConfigIni;$config = new ConfigIni(APP_PATH . 'app/config/config.ini');
允许我们以面向对象的方式操作文件。在本示例中,我们使用了一个.ini文件作为配置文件,不过,也支持对配置文件的详细适配。配置文件包含以下设置:
1234567891011121314[database]host
= localhostusername = rootpassword = secretname
= invo[application]controllersDir = app/controllers/modelsDir
= app/models/viewsDir
= app/views/pluginsDir
= app/plugins/formsDir
= app/forms/libraryDir
= app/library/baseUri
Phalcon没有任何预定义的惯例性设置。分段有助于我们去组织对应的设置选项。在这个文件中有两个分段,以用于其后的database和application。
自动加载出现在引导文件(public/index.php)的第二部分则是自动加载:
123456&?php * Auto-loader configuration */require APP_PATH . 'app/config/loader.php';
自动加载注册了一组由这个应用中所需要的类所组成的目录。
1234567891011121314&?php$loader = new Phalcon\Loader();$loader-&registerDirs(
APP_PATH . $config-&application-&controllersDir,
APP_PATH . $config-&application-&pluginsDir,
APP_PATH . $config-&application-&libraryDir,
APP_PATH . $config-&application-&modelsDir,
APP_PATH . $config-&application-&formsDir,
))-&register();
需要注意的是,上述代码中所注册的目录是配置文件中已经被定义(声明)的。唯一没有被预定义的目录是viewsDir,因为它包含了HTML文件和非PHP类文件。另外还要注意的是,我们使用了一个APP_PATH常量,这个常量已经在引导文件(public/index.php)中定义好了,以便于我们对项目的根目录路径的引用:
12345&?phpdefine('APP_PATH', realpath('..') . '/');
注册服务在引导文件中还需要的另一个文件是(app/config/services.php)。这个文件允许我们组织我们的服务,包括它们(服务)是否被使用。
123456&?php * Load application services */require APP_PATH . 'app/config/services.php';
注册服务在前面的教程中已经实现了,利用了一个闭包来延迟加载所需组件:
12345678910111213141516&?phpuse Phalcon\Mvc\Url as UrlProvider; * The URL component is used to generate all kind of URLs in the application */$di-&set('url', function () use ($config) {
$url = new UrlProvider();
$url-&setBaseUri($config-&application-&baseUri);
return $});
稍后我们再深入研究这个文件。
处理请求如果我们直接跳到文件(public/index.php)结尾,请求最终由Phalcon\Mvc\Application处理,它初始化并执行所有使应用程序运行的必要。
123456789&?phpuse Phalcon\Mvc\Application;$app = new Application($di);echo $app-&handle()-&getContent();
依赖注入观察上面代码的第一行,应用程序的类的构造函数接收变量$di作为参数。这个变量的目的是什么?Phalcon是一个高度松耦合的框架,所以我们需要一个作为胶水的组件来让一切共同协作。这个组件就是。它是一个服务容器,负责执行依赖注入和服务定位,以及实例化的所有组件所需的应用。
在容器中注册服务的途径有多种方式。在INVO这个项目中,大多数的服务都通过匿名/闭包函数来实现注册。得益于此,对象以慵懒的方式被实例化,从而减少程序所需的资源。
比如,在下面的代码片段中,session服务被注册进来。当应用程序需要访问会话数据的时候该匿名函数才会被调用:
1234567891011121314&?phpuse Phalcon\Session\Adapter\Files as Session;$di-&set('session', function () {
$session = new Session();
$session-&start();
return $});
在这里,我们有足够的自由来更换适配器,执行额外的初始化和更多的事情。请注意,该服务是以“session”命名来注册的。这是约定俗成的,允许框架在所述的服务容器中来识别有效服务。
一个请求会用到很多服务,并且逐个注册每个服务将是一个繁重的任务。由此,框架提供了一个叫做的变种框架,它基于,其任务是注册用于提供一个完整的全栈框架的所有服务。
123456789&?phpuse Phalcon\Di\FactoryDefault;$di = new FactoryDefault();
它以大部分框架所提供的服务和组件作为标准。如果我们需要重新定义某些服务,我们可以像上面一样把它再设置为session或是url,这就是变量$di存在的意义。
在下一个章节中,我们将看到如何在INVO中实现认证和授权。
教程1:通过示例快速入门通过这个入门教程,我们将引导您从零创建简单的带有注册表单的应用。 我们也将阐述框架行为的基本方面。如果您对Phalcon的自动代码生成工具有兴趣, 您可以查看 。
确认安装我们假设你已经安装了Phalcon。请查看你的phpinfo()输出了一个Phalcon部分引用或者执行以下代码片段:
1&?php print_r(get_loaded_extensions()); ?&
Phalcon扩展应该作为输出的一部分出现:
12345678910Array(
[0] =& Core
[1] =& libxml
[2] =& filter
[3] =& SPL
[4] =& standard
[5] =& phalcon
[6] =& pdo_mysql)
构建项目使用本教程的最好方法就是依次按照每一步来做。你可以得到完整的示例代码
文件结构Phalcon不会强制要求应用程序的开发遵循某些特定的文件结构。因为它是松耦合的,你可以实现Phalcon驱动的应用程序,以及使用对你来说最舒服的文件结构。
本教程的目的以此为起点,我们建议使用以下文件结构:
123456789tutorial/
controllers/
需要注意的是,你不需要任何有关Phalcon的library目录。该框架已经被加载到内存中,供您使用。
优美的URLS在本教程中,我们将使用相当(友好)URL。友好的URL不但利于SEO而且便于用户记忆。Phalcon支持一些最流行的Web服务器提供重写模块。不过让你的应用程序拥有友好的URL并不是强制性的,没有它们你可以同样轻松地开发。
在这个例子中,我们将使用Apache的重写模块。 让我们在/tutorial/.htaccess文件中创建几个重写规则:
123456&IfModule mod_rewrite.c&
RewriteEngine on
RewriteRule
^$ public/
RewriteRule
((?s).*) public/$1 [L]&/IfModule&
对该项目的所有请求都将被重定向到为public/文档根目录。此步骤可确保内部项目的文件夹仍然对公共访客隐藏,从而消除了一些安全威胁。
第二组规则将检查是否存在所请求的文件,如果存在所要请求的文件,就不需要Web服务器模块来重写:
1234567&IfModule mod_rewrite.c&
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^((?s).*)$ index.php?_url=/$1 [QSA,L]&/IfModule&
引导文件你需要创建的第一个文件就是引导文件。这个文件非常重要。因为它作为你的应用程序的基础,用它来控制应用程序的一切方面。 在这个文件中,你可以实现组件的初始化和应用程序的行为。
这个引导文件tutorial/public/index.php文件应该看起来是这样的:
12345678910111213141516171819202122232425262728293031323334353637383940414243&?phpuse Phalcon\Loader;use Phalcon\Mvc\View;use Phalcon\Mvc\Application;use Phalcon\Di\FactoryDefault;use Phalcon\Mvc\Url as UrlProvider;use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;try {
$loader = new Loader();
$loader-&registerDirs(array(
'../app/controllers/',
'../app/models/'
))-&register();
$di = new FactoryDefault();
$di-&set('view', function () {
$view = new View();
$view-&setViewsDir('../app/views/');
$di-&set('url', function () {
$url = new UrlProvider();
$url-&setBaseUri('/tutorial/');
$application = new Application($di);
echo $application-&handle()-&getContent();} catch (\Exception $e) {
echo "Exception: ", $e-&getMessage();}
自动加载我们可以看出,引导程序的第一部分是注册一个自动加载器。在这个应用程序里,它将用于加载控制器和模型类。例如,我们可以为控制器注册一个或多个目录来增加应用程序的灵活性的。在我们的例子中,我们使用了Phalcon\Loader组件。
有了它,我们可以加载使用各种策略类,但在这个例子中,我们选择了在预定义的目录中查找类:
12345678910111213&?phpuse Phalcon\Loader;$loader = new Loader();$loader-&registerDirs(
'../app/controllers/',
'../app/models/'
))-&register();
依赖管理在使用Phalcon时必须理解的一个非常重要的概念是 . 这听起来复杂,但实际上非常简单实用。
服务容器是一个全局存储的将要被使用的应用程序功能包。每次框架需要的一个组件时,会请求这个使用协定好名称的服务容器。因为Phalcon是一个高度松耦合的框架,
作为黏合剂,促使不同组件的集成,以一个透明的方式实现他们一起进行工作。
12345678&?phpuse Phalcon\Di\FactoryDefault;$di = new FactoryDefault();
的一个变体。为了让一切变得简单起来,它已注册了Phalcon的大多数组件。 因此,我们不需要一个一个去注册这些组件。在以后更换工厂服务的时候也不会有什么问题。
在接下来的部分,我们注册了视图(view)服务,告诉框架将要去指定的目录寻找视图文件。由于视图并非是一个对应的PHP类,它们不能被自动加载器加载。
服务可以通过多种方式进行注册,但在本教程中,我们将使用一个匿名函数 来实现:
123456789101112&?phpuse Phalcon\Mvc\View;$di-&set('view', function () {
$view = new View();
$view-&setViewsDir('../app/views/');
return $});
接下来,我们注册了一个基础URI服务,这样通过Phalcon生成包括我们之前设置的tutorial文件夹在内的所有的URI。 我们使用类 生成超链接,这将在本教程后续部分很重要。
123456789101112&?phpuse Phalcon\Mvc\Url as UrlProvider;$di-&set('url', function () {
$url = new UrlProvider();
$url-&setBaseUri('/tutorial/');
return $});
在这个文件的最后部分,我们发现 。其目的是初始化请求环境,并接收从路由而来的请求,接着分发任何发现的动作;然后收集所有的响应,并在过程完成后返回它们。
123456789&?phpuse Phalcon\Mvc\Application;$application = new Application($di);echo $application-&handle()-&getContent();
正如你所看到的,引导文件很短,我们并不需要引入任何其他文件。在不到30行的代码里,我们已经为自己设定一个灵活的MVC应用程序。
创建一个控制器默认情况下Phalcon会寻找一个名为Index的控制器。当请求中没有其他的控制器或动作时,则使用Index控制器作为起点。这个Index控制器 (app/controllers/IndexController.php) 看起来类似:
123456789101112&?phpuse Phalcon\Mvc\Controller;class IndexController extends Controller{
public function indexAction()
echo "&h1&Hello!&/h1&";
}}
控制器类必须有Controller后缀,且控制器动作必须有Action后缀。如果你从浏览器访问应用程序,你应该看到如下内容:
恭喜, 让Phalcon带你飞吧!
输出到视图从控制器发送打印到屏幕上有时是必要的,但是在MVC社区中的大多数纯粹主义者证明这样做不可取。一切必须传递给视图,视图负责在屏幕上输出数据。Phalcon将在最后执行的控制器的同名目录中,查找与最后执行动作的同名的视图。在我们的例子 (app/views/index/index.phtml)中 :
1&?php echo "&h1&Hello!&/h1&";
我们的控制器 (app/controllers/IndexController.php) 现在定义了一个空的动作:
123456789101112&?phpuse Phalcon\Mvc\Controller;class IndexController extends Controller{
public function indexAction()
}}
浏览器输出应该会保持不变。当这个动作执行结束时,
静态组件会自动创建。 学习更多关于
设计注册表单现在我们将修改index.phtml视图文件,添加一个超链接到一个名为signup的新控制器。我们的目标是在应用程序中可以让用户注册。
12345&?phpecho "&h1&Hello!&/h1&";echo $this-&tag-&linkTo("signup", "Sign Up Here!");
通过$this-&tag-&linkTo(&signup&, &Sign Up Here!&);生成的HTML代码显示一个锚 a HTML标签链接到一个新的控制器:
1&h1&Hello!&/h1& &a href="/tutorial/signup"&Sign Up Here!&/a&
我们使用类
去生成HTML标签。这是一个让我们构建HTML标记的实用类。 关于生成HTML更详细的文章可以查看 。
这是注册控制器 (app/controllers/SignupController.php)的代码:
123456789101112&?phpuse Phalcon\Mvc\Controller;class SignupController extends Controller{
public function indexAction()
}}
这个空的index动作整洁地传递已经定义好的表单给了一个视图文件(app/views/signup/index.phtml):
12345678910111213141516171819&h2&Sign up using this form&/h2&&?php echo $this-&tag-&form("signup/register"); ?& &p&
&label for="name"&Name&/label&
&?php echo $this-&tag-&textField("name") ?& &/p& &p&
&label for="email"&E-Mail&/label&
&?php echo $this-&tag-&textField("email") ?& &/p& &p&
&?php echo $this-&tag-&submitButton("Register") ?& &/p&&/form&
在浏览器中查看表单将显示类似的页面:
还提供了有用的方法来构建表单元素。
Phalcon\Tag::form() 方法只接受一个参数实例, 一个相对的uri到这个应用的一个控制器/动作。
通过单击Send按钮,您将注意到框架抛出了一个异常,这表明我们遗漏了在控制器中注册register动作。所以我们的public/index.php文件抛出这个异常:
Exception: Action “register” was not found on handler “signup”
定义该动作(register)就会移除这个异常:
1234567891011121314151617&?phpuse Phalcon\Mvc\Controller;class SignupController extends Controller{
public function indexAction()
public function registerAction()
}}
此时如果你再点击Send按钮,就会看到一个空白页。输入了名称和电子邮件这个用户应该被存储在数据库中。根据MVC的理念,数据库的交互必须通过模型来完成,以确保干净整洁的面向对象式的代码。
创建模型Phalcon带来了第一个完全用C语言编写的PHP ORM。它简化了开发,而不是增加了开发的复杂性。
在创建我们的第一个模型之前,我们需要在Phalcon以外创建一个数据库表。一个用来存储注册用户的简单数据表,可以这样定义:
123456CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(70) NOT NULL,
`email` varchar(70) NOT NULL,
PRIMARY KEY (`id`));
模型应该位于app/models目录 (app/models/Users.php)。这个模型对应的是上面的users表:
123456789101112&?phpuse Phalcon\Mvc\Model;class Users extends Model{
public $}
配置数据库连接为了能够使用一个数据库连接,然后通过我们的模型访问数据,我们需要在我们的引导过程设置它。数据库连接是我们的应用程序可以使用的数个组件中的另一个服务:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253&?phpuse Phalcon\Loader;use Phalcon\Di\FactoryDefault;use Phalcon\Mvc\View;use Phalcon\Mvc\Application;use Phalcon\Mvc\Url as UrlProvider;use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;try {
$loader = new Loader();
$loader-&registerDirs(array(
'../app/controllers/',
'../app/models/'
))-&register();
$di = new FactoryDefault();
$di-&set('db', function () {
return new DbAdapter(array(
=& "localhost",
"username" =& "root",
"password" =& "secret",
=& "test_db"
$di-&set('view', function () {
$view = new View();
$view-&setViewsDir('../app/views/');
$di-&set('url', function () {
$url = new UrlProvider();
$url-&setBaseUri('/tutorial/');
$application = new Application($di);
echo $application-&handle()-&getContent();} catch (\Exception $e) {
echo "Exception: ", $e-&getMessage();}
通过配置正确的数据库参数,我们的模型已经准备和应用程序的其余部分工作。
通过模型存储数据下一个步骤是将从表单接收的数据存储在数据表中。
1234567891011121314151617181920212223242526272829303132&?phpuse Phalcon\Mvc\Controller;class SignupController extends Controller{
public function indexAction()
public function registerAction()
$user = new Users();
$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();
}}
然后我们实例化用户类,它对应一个用户行记录。类的公共属性映射到用户表中的行记录的字段。在新记录中设置相应的值并调用save()方法将在数据库中存储相应的数据记录。save()方法返回一个布尔值,表示存储的数据是否成功。
ORM会自动转义输入以防止SQL注入,所以我们只需要将请求传递给save()方法即可。
附加的自动验证会验证字段定义为not null(强制输入)。如果我们不输入任何强制输入的注册表单中的字段,我们的屏幕就会看起来像这样:
结束语这是一个非常简单的教程,正如你所看到的,使用Phalcon很容易开始构建应用程序。Phalcon是一个在你的web服务器上无干扰、易开发、性能优的扩展框架。我们邀请你继续阅读手册,这样你就可以发现Phalcon提供的更多附加功能!Phalcon bulk insert performance. Models or Raw SQL [尔康批量插入的性能。模型或原始SQL] - 问题-字节技术
Phalcon bulk insert performance. Models or Raw SQL
尔康批量插入的性能。模型或原始SQL
问题 (Question)
Is there a way to do bulk inserts in phalcon php?
I tried inserting 10000 records using \Phalcon\Mvc\Model create and also the same using raw SQL: insert into 'tablename' (a, b, c) values (), (), (), ... ()
I set up this very simple test, and was surprised by the results
using \Phalcon\Mvc\Model took around 36 seconds
using raw sql took 3,6 seconds.
\Phalcon\Mvc\Model:
$transactionManager = new TransactionManager();
$transaction = $transactionManager-&get();
$entity = new Entity();
$entity-&setTransaction($transaction);
for($i = 0; $i & 10000; $i++){
$entity-&setValue1(rand(1,50));
$entity-&setValue2(rand(1,50));
$entity-&setValue3(rand(1,50));
$entity-&create();
$transaction-&commit();
$query = "insert into 'tablename' (a, b, c) values ";
for($i = 0; $i & 10000; $i++){
$values .= "(" . rand(1,50) . ", " . rand(1, 50). ", " . rand(1, 50). "),";
$values = substr($values, 0, strlen($values) - 1);
$query .= $
$this-&db-&query($query);
有没有办法在尔康PHP做批量插入?我试着用插入10000条记录\Phalcon\Mvc\Model create还原SQL相同的使用:insert into 'tablename' (a, b, c) values (), (), (), ... ()我建立了这个非常简单的测试,并对结果感到惊讶使用\尔康\ MVC模型花了大约36秒钟使用原始的SQL了6秒。\尔康\ MVC模型:$transactionManager = new TransactionManager();
$transaction = $transactionManager-&get();
$entity = new Entity();
$entity-&setTransaction($transaction);
for($i = 0; $i & 10000; $i++){
$entity-&setValue1(rand(1,50));
$entity-&setValue2(rand(1,50));
$entity-&setValue3(rand(1,50));
$entity-&create();
$transaction-&commit();
原始的SQL:$query = "insert into 'tablename' (a, b, c) values ";
for($i = 0; $i & 10000; $i++){
$values .= "(" . rand(1,50) . ", " . rand(1, 50). ", " . rand(1, 50). "),";
$values = substr($values, 0, strlen($values) - 1);
$query .= $
$this-&db-&query($query);
最佳答案 (Best Answer)
Phalcon\Mvc\Model is slow because it creates a PHQL statement for every INSERT, then parses it and translates into the SQL dialect supported by the current DBMS. PHQL parsing is what makes this slow.
If you need performance, you will have to generate the INSERT statement yourself.
尔康\ MVC模型的慢是因为它创造了一个为每个插入phql语句,然后将其转化到当前数据库支持的SQL方言。phql解析是什么使这个慢。如果您需要的性能,你需要生成INSERT语句中的自己。
本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:& 开始学习phalcon教程一:从实例开始学习
开始学习phalcon教程一:从实例开始学习
开始学习phalcon教程一:从实例开始学习
/zan1723.html
开始学习phalcon教程一:从实例开始学习 | 赞生博客 高端订制web开发工作组|做更漂亮的网站
在本教程中,我们将通过一个简单的注册表单案例来引导您使用Phalcon创建应用。我们稍后也会阐述框架的基本行为。如果你对Phalcon的自动代码生成工具感兴趣,你可以查看 。
Throughout this first tutorial, we’ll walk you through the creation of an application with a simple registration form from the ground up. We will also explain the basic aspects of the framework’s behavior. If you are interested in automatic code generation tools for Phalcon, you can check our .
检查Phalcon是否安装
我们假设你已经成功安装Phalcon。检查 phpinfo() 输出,查找是否有”Phalcon”这一节,又或者执行下面的代码片断:
We’ll assume you have Phalcon installed already. Check your phpinfo() output for a section referencing “Phalcon” or execute the code snippet below:
&?php print_r(get_loaded_extensions()); ?&
执行结果中应该会出现Phaclon扩展信息:
The Phalcon extension should appear as part of the output:
[0] =& Core
[1] =& libxml
[2] =& filter
[3] =& SPL
[4] =& standard
[5] =& phalcon
[6] =& mysql
[7] =& mysqli
使用本教程最好的方法是按照每个步骤依次进行。你可以在这里获取完整代码, 。
The best way to use this guide is to follow each step in turn. You can get the complete code .
Phalcon对于应用开发并没有特殊的文件结构要求。基于她是松耦合这一事实,当你使用Phalcon进行开发时,你可以使用任何你喜欢的文件结构。
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:
controllers/
注意,你并不需要有一个专门的”library”目录来存放Phalcon提供的库。因为她都已经在内存中加载好了,只等你来使用了(译者注: 我已等待了千年,为何良人“不回来”?)。
Note that you don’t need any “library” directory related to Phalcon. The framework is available in memory, ready for you to use.
在本教程中我们将使用漂亮(友好)的URL。友好的URL不仅利于搜索引擎优化(SEO),也方便用户记住。Phalcon支持几乎所有主流 WEB 服务器的重写模块。不过,漂亮的URL对于你的应用来说不是必须的,没有它们也能照样开发。
We’ll use pretty (friendly) urls for this tutorial. Friendly URLs are better for SEO as well as they are 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 easy develop without them.
在这个示例中我们将使用Apache的重写模块。让我们在 /.htaccess 文件中创建一对重写规则吧:
In this example we’ll use the rewrite module for Apache. Let’s create a couple of rewrite rules in the /.htaccess file:
#/.htaccess
&IfModule mod_rewrite.c&
RewriteEngine on
RewriteRule
^$ public/
RewriteRule
(.*) public/$1 [L]
&/IfModule&
所有对该项目的请求都会重定向到 public/ 目录下,这使得 public 目录成为实际的网站根目录。这一步是为了确保内部的项目文件对外不可见,以避开安全威胁。
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 posing security threats.
重定向的第二步将会检查被请求的文件是否存在,如果文件存在则不会被WEB服务器重定向。
The second set of rules will check if the requested file exists, and if it does it doesn’t have to be rewitten by the web server module:
#/public/.htaccess
&IfModule mod_rewrite.c&
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
&/IfModule&
你需要创建的第一个文件是引导文件。该文件非常重要,是整个应用的基础,让你能控制应用的方方面面。在引导文件中你可以实现组件初以及应用行为的初始化。
The first file you need to create is the bootstrap file. This fi 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.
引导文件 public/index.php 文件看起来应该是这样的:
The public/index.php file should look like:
//Register an autoloader
$loader = new \Phalcon\Loader();
$loader-&registerDirs(array(
'../app/controllers/',
'../app/models/'
))-&register();
//Create a DI
$di = new Phalcon\DI\FactoryDefault();
//Setting up the view component
$di-&set('view', function(){
$view = new \Phalcon\Mvc\View();
$view-&setViewsDir('../app/views/');
//Handle the request
$application = new \Phalcon\Mvc\Application();
$application-&setDI($di);
echo $application-&handle()-&getContent();
} catch(\Phalcon\Exception $e) {
echo "PhalconException: ", $e-&getMessage();
在引导文件的第一部分,我们注册了一个类-自动加载器。它将会用于加载应用程序的控制器类和模型类。例如,为了提升应用的灵活性,我们可能会注册一个或多个控制器目录。在我们的示例中,我们已经使用了 Phalcon\Loader 组件。
The first part that we find in the boostrap 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:
$loader = new \Phalcon\Loader();
$loader-&registerDirs(
'../app/controllers/',
'../app/models/'
)-&register();
使用Phalcon必须要理的一个重要的概念就是
。这个…听起来可能很复杂,但实际上简单又实用。
A very important concept that must be understood when working with Phalcon is its . It may sound complex but is actually very simple and practical.
服务容器就好比一个大箱子,里面存放了应用程序后续要使用的各种服务(全局资源)。每当框架需要某个组件时,都会使用预先约定好的服务名称向容器请求。鉴于Phalcon是一个解耦框架, Phalcon\DI 扮演着胶水的角色,以促进不同组件透明地协同工作。
A service container is a bag where we globally store the services that our application will use to work. Each time the framework requires a component, will ask the container using a name service agreed. 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.
//Create a DI
$di = new Phalcon\DI\FactoryDefault();
是 Phalcom\DI 的一个变种。为了让事情变得更简单,它注册了Phalcon框架的大部分组件,所以我们就不必再一个个去注册它们了。即使之后想更换这个工厂服务也不会有任何问题。
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 can not be charged with an autoloader.
注册服务的方法不只一种,但是在本教程中我们将使用匿名函数的方法:
Services can be registered in several ways, but for our tutorial we’ll use lambda functions:
//Setting up the view component
$di-&set('view', function(){
$view = new \Phalcon\Mvc\View();
$view-&setViewsDir('../app/views/');
在引导文件的最后一部分,我们发现了
组件。它的职责是初始化请求环境、路由来访请求,然后调度请求到任何可发现的动作上。当处理完毕后,它收集所有响应并返回给浏览器。
In the last part of this file, we find . Its purpose is to initialize the request environment, route the incoming request, and then dispatch an it aggregates any responses and returns them when the process is complete.
$application = new \Phalcon\Mvc\Application();
$application-&setDI($di);
echo $application-&handle()-&getContent();
正如你所看到的,引导文件不仅简短,而且不用引入额外的文件。我们用不超过30行代码为自己制定了一个灵活的MVC应用。
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会查找名为”Index”的控制器。当请求中没有控制器和动作传入时,它是整个应用的起点。Index 控制器 (app/controllers/IndexController.php) 示例代码如下:
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:
class IndexController extends \Phalcon\Mvc\Controller
public function indexAction()
echo "&h1&Hello!&/h1&";
控制器类名必须要以”Controller”结尾,控制器动作必须要以”Action”结尾。如果你从浏览器访问该应用,你应该看到这样的情景:
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:
恭喜您,你已经和Phaclon一起在蓝天飞翔了!
Congratulations, you’re flying with Phalcon!
向视图发送输出
虽然有时我们不得不从控制器发送输出到屏幕,但这种方式是不可取的,纯粹的MVC实践者将会证明这一点。视图才是负责发送输出到屏幕的组件,因此所有信息都必须传送给它。Phalcon将会在以 最后执行的控制器命名的 文件夹中查找 以最后执行的动作命名的 视图文件。在本示例中是(app/views/index/index.phtml):
Sending output on 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 which 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):
&?php echo "&h1&Hello!&/h1&";
现在我们在控制器(app/controllers/IndexController.php)中定义一个空动作:
Our controller (app/controllers/IndexController.php) now has an empty action definition:
class IndexController extends \Phalcon\Mvc\Controller
public function indexAction()
浏览器输出应该和之前一样。当动作执行结束时,静态组件
会被自动创建。要了解更多关于视图的内容,
The browser output should remain the same. The
static component is automatically created when the action execution has ended. Learn more about
设计注册表单
现在,让我们来修改index.phtml视图文件,在文件中添加到新控制器”signup”的链接。目的就是允许用户在我们的应用中注册。
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 in our application.
echo "&h1&Hello!&/h1&";
echo Phalcon\Tag::linkTo("signup", "Sign Up Here!");
生成的HTML代码将显示一个链接到新控制器的”A”标签:
The generated HTML code displays an “A” html tag linking to a new controller:
&h1&Hello!&/h1& &a href="/test/signup"&Sign Up Here!&/a&
为了生成这个”A”标签,我们使用
类。这是一个工具类,让我们能够以框架约定的形式创建HTML标签。要了解更多关于生成HTML的内容,
To generate the tag we use the class . 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 be
下面是Signup控制器(app/controllers/SignupController.php):
Here is the controller Signup (app/controllers/SignupController.php):
class SignupController extends \Phalcon\Mvc\Controller
public function indexAction()
空的index动作不会传递任何信息到定义表单的视图中:
The empty index action gives the clean pass to a view with the form definition:
&?php use Phalcon\T ?&
&h2&Sign using this form&/h2&
&?php echo Tag::form("signup/register"); ?&
&label for="name"&Name&/label&
&?php echo Tag::textField("name") ?&
&label for="name"&E-Mail&/label&
&?php echo Tag::textField("email") ?&
&?php echo Tag::submitButton("Register") ?&
在浏览器中查看该表单,应该是这个样子:
Viewing the form in your browser will show something like this:
组件还提供了一些有效构建表单元素的方法。
also provides useful methods to build form elements.
Phalcon\Tag::form 方法目前只接受一个参数:应用中某 控制器/动作 的相对URI。
The Phalcon\Tag::form method receives only one parameter for instance, a relative uri to a controller/action in the application.
通过点击”Send”按钮,你将会看到框架抛出的异常,提示我们在”signup”控制器中缺少”register”动作。这个异常是 public/index.php 文件抛出的:
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”. This exception is thrown by our public/index.php file:
PhalconException: Action “register” was not found on controller “signup”
只要实现了这个方法,异常就会消失:
Implementing that method will remove the exception:
class SignupController extends \Phalcon\Mvc\Controller
public function indexAction()
public function registerAction()
当再次点击”Send”按钮的时候,你将会看到一个空白页面。用户输入的姓名和邮箱应该被储存在数据库中。按照MVC的纲领,为了写出纯粹干净的面向对象,数据库交互应该在模型中完成。
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.
Phalcon给PHP带来了第一个C语言级的ORM。这并没有增加开发复杂度,反而大大简化了这个过程。
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 a database table to map it to. A simple table to store registered users can be defined like this:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(70) NOT NULL,
`email` varchar(70) NOT NULL,
PRIMARY KEY (`id`)
模型文件应该放在 app/models 目录下。关联”users”表的模型类:
A model should be located in the app/models directory. The model mapping to “users” table:
class Users extends \Phalcon\Mvc\Model
设置数据库连接
为了使用数据库连接,以及后面通过模型访问数据,我们需要在引导程序中指定它。数据库连接不过是我们应用的另一个服务罢了,设置好后也能被其他组件使用:
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 sereral components:
//Register an autoloader
$loader = new \Phalcon\Loader();
$loader-&registerDirs(array(
'../app/controllers/',
'../app/models/'
))-&register();
//Create a DI
$di = new Phalcon\DI\FactoryDefault();
//Set the database service
$di-&set('db', function(){
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" =& "localhost",
"username" =& "root",
"password" =& "secret",
"dbname" =& "test_db"
//Setting up the view component
$di-&set('view', function(){
$view = new \Phalcon\Mvc\View();
$view-&setViewsDir('../app/views/');
//Handle the request
$application = new \Phalcon\Mvc\Application();
$application-&setDI($di);
echo $application-&handle()-&getContent();
} catch(\Phalcon\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.
使用模型存储数据
接收来自表单的数据,然后下一步把它们存储到数据库-表中。
Receiving data from the form and storing them in the table is the next step.
class SignupController extends \Phalcon\Mvc\Controller
public function indexAction()
public function registerAction()
//Request variables from html form
$name = $this-&request-&getPost("name", "string");
$email = $this-&request-&getPost("email", "email");
$user = new Users();
$user-&name = $
$user-&email = $
//Store and check for errors
if ($user-&save() == true) {
echo "Thanks for register!";
echo "Sorry, the following problems were generated: ";
foreach ($user-&getMessages() as $message) {
echo $message-&getMessage(), "&br/&";
我们永远不能信任用户输入。对于用户输入的变量,我们必须有相应的过滤器适用于它们,对其内容进行
。这样能让我们的应用更安全,因为它能避免一些常见的攻击,如SQL注入等。
We can never trust data sent from a user. Variables passed into our application, from user input, need to have a filter applied to them so as to
their contents. This makes the application more secure because it avoids common attacks like SQL injections.
在本教程中,我们对“姓名”这个变量使用“字符串”过滤器,以保证用户的输入中不会有任何危险字符。
组件使得这一切变得简单易用,因为它是通过依赖容器注入到 getPost 方法中。
In our tutorial we apply the filter “string” to the “name” variable to ensure that user did not sent us any malicious characters. The component
makes this task trivial, since it is injected from the dependency container into the getPost call.
然后我们实例化Users类,它会关联到某条用户记录。类的公有属性会关联到users表中某条记录的所有字段。创建一条新记录,并为其字段设置相应的值,然后调用save()方法,便会在数据库中存储该记录。save()方法会给我们返回一个布尔值,以表明数据存储过程成功与否。
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 informs us on whether the storing of the data was successful or not.
对于非空(必填)字段,会对其自动进行非空过滤。如果有必填字段没填,我们便会得到如下提示:
Additional validation happens automatically on fields that are not null (required). If we don’t type any of the required fields our screen will look like this:
这是一个非常简单的教程,如你所见,使用Phalcon创建应用是如此的简单。Phalcon作为一个扩展存在,并不会增加开发复杂度,更不会影响现有功能。我们邀请您继续阅读手册的其他部分,这样你便能发现Phalcon提供的其他功能!
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 features1 offered by Phalcon!
示例应用程序
下面提供了一些基于Phaclon的应用,它们是你学习时更完善的示例:
The following Phalcon powered applications are also available, providing more complete examples:
: Invoice generation application. Allows for management of products, companies, product types. etc.
: Multilingual and advanced routing application.
转载请注明: >>
本文的评论功能被关闭了.
关注“Linux运维技术”微信公众号
2016年九月
12131415161718
19202122232425
2627282930

我要回帖

更多关于 phalcon 模型 的文章

 

随机推荐