Project Versions

Table Of Contents

Welcome!

欢迎使用Phalcon php 框架,我们的使命是给你一个开发网站及应用的高级工具,而你却不必担心性能问题.

什么是 Phalcon?

Phalcon 是一个开源的,全堆栈的,用C语言写成的php5框架,专为高性能设计。你不需要学习和使用C语言的功能,因为这是一个PHP框架,只不过用C写成而已。同时Phalcon是松耦合的,您可以根据需要使用其他组件。

Phalcon不只是性能优越,我们的目标是让它强大而且易于使用!

译者说明

一般都是直接看英文资料,大都能看得懂。但看到Phalcon框架如此优秀,在学习后就想和大家分享,但发现国内的人几乎没有使用的,故想翻译一下,一旦翻译才发现读懂和译出一篇好文章真的不太一样。 故前一期翻译的部分章节有点生硬,等有空的时候再回头重译吧,后面的一部分也是以英文文档为基础,但并不再是逐句翻译了。

09年左右,大量的框架出现,我看过的框架不下20种,最先看到的可能就是php.MVC了,这是一个按照struts 1x编写的,只不过同时加载的类库太多了,效率不高而且不太完善。

后来稍有名的包括 cakephp, Symfony, Akelos, Prado, Kohana等,最近几年流行的就是 zf, yii, ci等,当然还有国内几个比较有名的框架,如fleaphp, thinkphp等。

在上面的一些框架中,我比较感冒的还是ci,yii,thinkphp等。ci,thinkphp够简单,速度也不错。yii是生活在国外的华人开发,功能够全而强大,速度也不错,国内的应用也不少。

一直不太喜欢zf,记得几年前就和同行朋友聊天的时候说,像ZEND公司完全可以用C语言开发出一个扩展来,这样效率会高得多,为毛非得用PHP开发呢,事实被我验证了,但开发扩展的不是ZEND公司,而是国内一个PHP大鸟,人称鸟哥。这个框架就是非常出名的YAF,因此YAF扩展是我必装的扩展之一。同时这也是我发现的第一个C语言写的扩展框架。

但YAF的缺点是,功能非常不完善,在我看来只是简单实现了MVC结构及路由,分发等功能,像一些ORM之类的功能完全没有开发,作者好像也没有开发的意思:)

后来就发现了Phalcon,一看文档就爱上了她,功能,速度等都是我想要的,我花了一周时间看文档学习她,并在一个下午的过程中,发现了文档中的三个错误并提交了这些错误:),我决定为完善它也贡献一点自己的力量。

本文档的中文地址存放在 http://phalcon.5iunix.net

Github上的地址为: https://github.com/netstu/phalcondocs ,您如果发现有些地方译的有些操蛋,烦请你fork它,并完善她。

目录

我们的目的

现在有很多各种各样的PHP框架,但他们没有一个像Phalcon一样(真的,在这点上请相信我)

几乎所有的程序员都喜欢使用框架,这主要是因为框架提供了很多的功能,已经经过了大量的测试,因此保持代码DRY(不要重复造轮子)。然而,框架本身需要包含大量的文件来解释和执行实际应用中的每个请求,因此会降低应用程序的性能,影响用户体验。

The Question

为什么我们不能有这样一个框架,保持它的优势的同时,没有或者很少有缺点呢?

这就是为什么Phalcon诞生了!

在过去的几个月中,我们已经广泛地研究了PHP的行为,调查区域为显着优化(大或小)。 通过Zend引擎的理解,我们设法消除不必要的验证,压缩的代码,进行优化和生成的 低级别的解决方案,从而使Phalcon实现最大的性能。

Why?

  • The use of frameworks has become mandatory in professional development with PHP
  • 框架提供了结构化的理念,以轻松维护项目,编写更少的代码,使工作变得更有趣

Inner workings of PHP?

  • PHP是一种动态的和弱变量类型语言。每次一个二进制运算(例如,2+“2”),PHP就会检查操作数的类型来进行类型转换
  • PHP是解释型语言。主要的缺点是性能上的损失
  • 每一个请求,它必须首先解释.
  • 如果不使用字节码缓存(如APC),则任何时间的任何一个请求它都会进行语法检查

How traditional PHP frameworks work?

  • Many files with classes and functions are read on every request made. Disk reading is expensive in terms of performance, especially when the file structure includes deep folders
  • Modern frameworks use lazy loading (autoload) to increase performance (for load and execute only the code needed)
  • Continuous loading or interpreting is expensive and impacts performance
  • The framework code does not change very often, therefore an application needs to load and interpret it every time a request is made

How does a PHP C-extension work?

  • C extensions are loaded together with PHP one time on the web server’s daemon start process
  • Classes and functions provided by the extension are ready to use for any application
  • The code isn’t interpreted because is already compiled to a specific platform and processor

How does Phalcon work?

  • Components are loosely coupled. With Phalcon, nothing is imposed on you: you’re free to use the full framework, or just some parts of it as a glue components.
  • Low-level optimizations provides the lowest overhead for MVC-based applications
  • Interact with databases with maximum performance by using a C-language ORM for PHP
  • Phalcon directly accesses internal PHP structures optimizing execution in that way as well

Conclusion

Phalcon is an effort to build the fastest framework for PHP. You now have an even easier and robust way to develop applications without be worrying about performance. Enjoy!

框架基准测试

在过去,开发的web应用程序,性能问题并不是作为首要考虑的问题之一。因为硬件可以填补这方面的不足。然后,当Google决定把网站的速度作为搜索排名的条件之一时,性能的重要性就体现出来了。

以下的基准测试,将展示Phalcon和其他传统的PHP框架的性能对比,这些基准框架的版本都是最新的稳定版本。

我们欢迎程序员利用我们的基准测试程序进行测试,如果您有更好的优化方案或意见,请 write us. Check out source at Github

测试的环境?

所有的框架都开启了 APC 缓存,且禁用了apache mod_rewrite模块,以避免产生额外的性能开销.

下面是测试的硬件环境:

  • Operating System: Mac OS X Lion 10.7.4
  • Web Server: Apache httpd 2.2.22
  • PHP: 5.3.15
  • CPU: 2.04 Ghz Intel Core i5
  • Main Memory: 4GB 1333 MHz DDR3
  • Hard Drive: 500GB SATA Disk

PHP version and info:

_images/bench-4.png

APC settings:

_images/bench-5.png

List of Benchmarks

Hello World Benchmark
How the benchmarks were performed?

We created a “Hello World” benchmark seeking to identify the smallest load overhead of each framework. Many people don’t like this kind of benchmark because real-world applications require more complex features or structures. However, these tests identify the minimum time spent by each framework to perform a simple task. Such a task represents the mimimum requirement for every framework to process a single request.

More specifically, the benchmark only measures the time it takes for a framework to start, run an action and free up resources at the end of the request. Any PHP application based on an MVC architecture will require this time. Due to the simplicity of the benchmark, we ensure that the time needed for a more complex request will be higher.

A controller and a view have been created for each framework. The controller “say” and action “hello”. The action only sends data to the view which displays it (“Hello!”). Using the “ab” benchmark tool we sent 1000 requests using 5 concurrent connections to each framework.

What measurements were recorded?

These were the measurements we record to identify the overall performance of each framework:

  • Requests per second
  • Time across all concurrent requests
  • Number of included PHP files on a single request (measured using function get_included_files.
  • Memory Usage per request (measured using function memory_get_usage.
Pariticipant Frameworks
Results
Yii (YII_DEBUG=false) Version yii-1.1.12.b600af
# ab -n 1000 -c 5 http://localhost/bench/yii/index.php?r=say/hello
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/yii/index.php?r=say/hello
Document Length:        61 bytes

Concurrency Level:      5
Time taken for tests:   1.174 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      254000 bytes
HTML transferred:       61000 bytes
Requests per second:    851.83 [#/sec] (mean)
Time per request:       5.870 [ms] (mean)
Time per request:       1.174 [ms] (mean, across all concurrent requests)
Transfer rate:          211.29 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    6   2.5      5      20
Processing:     0    0   0.4      0       6
Waiting:        0    0   0.3      0       6
Total:          2    6   2.5      5      20

Percentage of the requests served within a certain time (ms)
  50%      5
  66%      6
  75%      7
  80%      7
  90%      9
  95%     11
  98%     14
  99%     15
 100%     20 (longest request)
Symfony Version 2.0.11
# ab -n 1000 -c 5 http://localhost/bench/Symfony/web/app.php/say/hello/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/Symfony/web/app.php/say/hello/
Document Length:        16 bytes

Concurrency Level:      5
Time taken for tests:   1.848 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      249000 bytes
HTML transferred:       16000 bytes
Requests per second:    541.01 [#/sec] (mean)
Time per request:       9.242 [ms] (mean)
Time per request:       1.848 [ms] (mean, across all concurrent requests)
Transfer rate:          131.55 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    9   4.8      8      61
Processing:     0    0   0.6      0      15
Waiting:        0    0   0.6      0      15
Total:          4    9   4.8      8      61

Percentage of the requests served within a certain time (ms)
  50%      8
  66%      9
  75%     11
  80%     12
  90%     15
  95%     18
  98%     22
  99%     30
 100%     61 (longest request)
CodeIgniter 2.1.0
# ab -n 1000 -c 5 http://localhost/bench/codeigniter/index.php/say/hello
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/codeigniter/index.php/say/hello
Document Length:        16 bytes

Concurrency Level:      5
Time taken for tests:   1.159 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      209000 bytes
HTML transferred:       16000 bytes
Requests per second:    862.58 [#/sec] (mean)
Time per request:       5.797 [ms] (mean)
Time per request:       1.159 [ms] (mean, across all concurrent requests)
Transfer rate:          176.05 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    6   3.3      5      34
Processing:     0    0   1.5      0      34
Waiting:        0    0   1.5      0      34
Total:          2    6   3.5      5      35

Percentage of the requests served within a certain time (ms)
  50%      5
  66%      6
  75%      6
  80%      7
  90%      8
  95%     12
  98%     17
  99%     24
 100%     35 (longest request)
Kohana 3.2.0
# ab -n 1000 -c 5 http://localhost/bench/kohana/index.php/say/hello
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/kohana/index.php/say/hello
Document Length:        15 bytes

Concurrency Level:      5
Time taken for tests:   1.375 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      223000 bytes
HTML transferred:       15000 bytes
Requests per second:    727.07 [#/sec] (mean)
Time per request:       6.877 [ms] (mean)
Time per request:       1.375 [ms] (mean, across all concurrent requests)
Transfer rate:          158.34 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    7   3.3      6      37
Processing:     0    0   0.6      0      10
Waiting:        0    0   0.4      0       6
Total:          3    7   3.3      6      37

Percentage of the requests served within a certain time (ms)
  50%      6
  66%      7
  75%      8
  80%      8
  90%     10
  95%     13
  98%     16
  99%     20
 100%     37 (longest request)
Fuel 1.2.1
# ab -n 1000 -c 5 http://localhost/bench/fuel/say/hello
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/fuel/public/say/hello
Document Length:        16 bytes

Concurrency Level:      5
Time taken for tests:   1.759 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      209000 bytes
HTML transferred:       16000 bytes
Requests per second:    568.41 [#/sec] (mean)
Time per request:       8.796 [ms] (mean)
Time per request:       1.759 [ms] (mean, across all concurrent requests)
Transfer rate:          116.01 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    9   4.3      8      51
Processing:     0    0   1.3      0      34
Waiting:        0    0   1.3      0      34
Total:          4    9   4.4      8      51

Percentage of the requests served within a certain time (ms)
  50%      8
  66%      9
  75%     10
  80%     11
  90%     13
  95%     17
  98%     22
  99%     26
 100%     51 (longest request)
Cake 2.1.3
# ab -n 10 -c 5 http://localhost/bench/cake/say/hello
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient).....done


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/cake/say/hello
Document Length:        16 bytes

Concurrency Level:      5
Time taken for tests:   30.051 seconds
Complete requests:      10
Failed requests:        0
Write errors:           0
Total transferred:      1680 bytes
HTML transferred:       160 bytes
Requests per second:    0.33 [#/sec] (mean)
Time per request:       15025.635 [ms] (mean)
Time per request:       3005.127 [ms] (mean, across all concurrent requests)
Transfer rate:          0.05 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    2   3.6      0      11
Processing: 15009 15020   9.8  15019   15040
Waiting:        9   21   7.9     25      33
Total:      15009 15022   8.9  15021   15040

Percentage of the requests served within a certain time (ms)
  50%  15021
  66%  15024
  75%  15024
  80%  15032
  90%  15040
  95%  15040
  98%  15040
  99%  15040
 100%  15040 (longest request)
Zend Framework 1.11.11
# ab -n 10 -c 5 http://localhost/bench/zendfw/public/say/hello
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/zendfw/public/say/hello
Document Length:        16 bytes

Concurrency Level:      5
Time taken for tests:   3.086 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      209000 bytes
HTML transferred:       16000 bytes
Requests per second:    324.02 [#/sec] (mean)
Time per request:       15.431 [ms] (mean)
Time per request:       3.086 [ms] (mean, across all concurrent requests)
Transfer rate:          66.13 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   15   6.1     14      61
Processing:     0    0   1.7      0      37
Waiting:        0    0   1.7      0      36
Total:          8   15   6.1     14      61

Percentage of the requests served within a certain time (ms)
  50%     14
  66%     16
  75%     17
  80%     18
  90%     23
  95%     27
  98%     33
  99%     37
 100%     61 (longest request)
Laravel 3.2.5
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/laravel/public/say/hello
Document Length:        15 bytes

Concurrency Level:      5
Time taken for tests:   2.353 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      831190 bytes
HTML transferred:       15000 bytes
Requests per second:    424.97 [#/sec] (mean)
Time per request:       11.765 [ms] (mean)
Time per request:       2.353 [ms] (mean, across all concurrent requests)
Transfer rate:          344.96 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   12   5.6     10      56
Processing:     0    0   0.6      0      10
Waiting:        0    0   0.5      0      10
Total:          5   12   5.6     10      56

Percentage of the requests served within a certain time (ms)
  50%     10
  66%     12
  75%     13
  80%     15
  90%     18
  95%     22
  98%     29
  99%     36
 100%     56 (longest request)
Nette 2.0.4
# ab -n 1000 -c 5 http://localhost/bench/nette/www/index.php

This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/helloworld/nette/www/index.php
Document Length:        205 bytes

Concurrency Level:      5
Time taken for tests:   3.569 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      448000 bytes
HTML transferred:       205000 bytes
Requests per second:    280.18 [#/sec] (mean)
Time per request:       17.846 [ms] (mean)
Time per request:       3.569 [ms] (mean, across all concurrent requests)
Transfer rate:          122.58 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   18   6.6     16      63
Processing:     0    0   1.0      0      20
Waiting:        0    0   1.0      0      20
Total:          9   18   6.6     16      63

Percentage of the requests served within a certain time (ms)
  50%     16
  66%     19
  75%     20
  80%     22
  90%     27
  95%     31
  98%     37
  99%     39
 100%     63 (longest request)
Phalcon Version 0.5.0
# ab -n 1000 -c 5 http://localhost/bench/phalcon/index.php?_url=/say/hello
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/phalcon/index.php?_url=/say/hello
Document Length:        16 bytes

Concurrency Level:      5
Time taken for tests:   0.419 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      209000 bytes
HTML transferred:       16000 bytes
Requests per second:    2386.74 [#/sec] (mean)
Time per request:       2.095 [ms] (mean)
Time per request:       0.419 [ms] (mean, across all concurrent requests)
Transfer rate:          487.14 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    2   1.1      2      17
Processing:     0    0   0.1      0       3
Waiting:        0    0   0.1      0       2
Total:          1    2   1.1      2      17

Percentage of the requests served within a certain time (ms)
  50%      2
  66%      2
  75%      2
  80%      2
  90%      3
  95%      4
  98%      5
  99%      7
 100%     17 (longest request)
Graphs

The first graph shows how many requests per second each framework was able to accept. The second shows the average time across all concurrent requests.

Conclusion

The compiled nature of Phalcon offers extraordinary performance that outperforms all other frameworks measured in these benchmarks.

Micro Benchmark
How the benchmarks were performed?

We created a “Hello World” benchmark seeking to identify the smallest load overhead of each framework. Similar to the benchmark made with Frameworks.

Using a route for the HTTP method ‘GET’ we pass a parameter to a handler returning a “Hello $name” response.

What measurements were recorded?

These were the measurements we record to identify the overall performance of each framework:

  • Requests per second
  • Time across all concurrent requests
  • Number of included PHP files on a single request (measured using function get_included_files.
  • Memory Usage per request (measured using function memory_get_usage.
Pariticipant Frameworks
Results
Slim Framework
# ab -n 1000 -c 5 http://localhost/bench/micro/slim/say/hello/Sonny
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/micro/slim/say/hello/Sonny
Document Length:        13 bytes

Concurrency Level:      5
Time taken for tests:   0.882 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      206000 bytes
HTML transferred:       13000 bytes
Requests per second:    1134.21 [#/sec] (mean)
Time per request:       4.408 [ms] (mean)
Time per request:       0.882 [ms] (mean, across all concurrent requests)
Transfer rate:          228.17 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    4   2.4      4      33
Processing:     0    0   0.5      0      11
Waiting:        0    0   0.5      0      11
Total:          2    4   2.4      4      33

Percentage of the requests served within a certain time (ms)
  50%      4
  66%      4
  75%      5
  80%      5
  90%      6
  95%      8
  98%     12
  99%     14
 100%     33 (longest request)
Silex
# ab -n 1000 -c 5 http://localhost/bench/micro/silex/say/hello/Sonny
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/micro/silex/say/hello/Sonny
Document Length:        12 bytes

Concurrency Level:      5
Time taken for tests:   2.228 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      225000 bytes
HTML transferred:       12000 bytes
Requests per second:    448.75 [#/sec] (mean)
Time per request:       11.142 [ms] (mean)
Time per request:       2.228 [ms] (mean, across all concurrent requests)
Transfer rate:          98.60 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   11   5.1     10      44
Processing:     0    0   1.1      0      26
Waiting:        0    0   1.1      0      26
Total:          5   11   5.1     10      45

Percentage of the requests served within a certain time (ms)
  50%     10
  66%     12
  75%     13
  80%     14
  90%     17
  95%     20
  98%     25
  99%     29
 100%     45 (longest request)
Phalcon 0.5.0
# ab -n 1000 -c 5 http://localhost/bench/micro/phalcon/say/hello/Sonny
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)


Server Software:        Apache/2.2.22
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/micro/phalcon/say/hello/Sonny
Document Length:        12 bytes

Concurrency Level:      5
Time taken for tests:   0.397 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      205000 bytes
HTML transferred:       12000 bytes
Requests per second:    2516.74 [#/sec] (mean)
Time per request:       1.987 [ms] (mean)
Time per request:       0.397 [ms] (mean, across all concurrent requests)
Transfer rate:          503.84 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    2   0.9      2      11
Processing:     0    0   0.2      0       5
Waiting:        0    0   0.2      0       4
Total:          1    2   0.9      2      11

Percentage of the requests served within a certain time (ms)
  50%      2
  66%      2
  75%      2
  80%      2
  90%      3
  95%      4
  98%      5
  99%      5
 100%     11 (longest request)
Graphs

The first graph shows how many requests per second each framework was able to accept. The second shows the average time across all concurrent requests.

Conclusion

The compiled nature of Phalcon offers extraordinary performance that outperforms all other frameworks measured in these benchmarks.

ChangeLog

New in version 1.0: Update Mar-20-2012: Benchmarks redone changing the apc.stat setting to Off. More Info

Changed in version 1.1: Update May-13-2012: Benchmarks redone PHP plain templating engine instead of Twig for Symfony. Configuration settings for Yii were also changed as recommended.

Changed in version 1.2: Update May-20-2012: Fuel framework was added to benchmarks.

Changed in version 1.3: Update Jun-4-2012: Cake framework was added to benchmarks. It is not however present in the graphics, since it takes 30 seconds to run only 10 of 1000.

Changed in version 1.4: Update Ago-27-2012: PHP updated to 5.3.15, APC updated to 3.1.11, Yii updated to 1.1.12, Phalcon updated to 0.5.0, Added Laravel, OS updated to Mac OS X Lion. Hardware upgraded.

安装

PHP extensions require a slightly different installation method to a traditional php-based library or framework. You can either download a binary package for the system of your choice or build it from the sources.

During the last few months, we have extensively researched PHP’s behavior, investigating areas for significant optimizations (big or small). Through understanding of the Zend Engine, we managed to remove unecessary validations, compacted code, performed optimizations and generated low-level solutions so as to achieve maximum performance from Phalcon.

Phalcon compiles from PHP 5.3.1, but due to old PHP bugs causing memory leaks, we highly recommend you to use at least PHP 5.3.11 or greater.

Windows

在windows上安装任何扩展都是很简单的,安装phalcon也是一样,下载.dll文件,放到extension目录,然后修改php.ini文件,加入以下行:

extension=php_phalcon.dll

重启web server.

以下视频是教你如何一步一步在windows上安装phalcon

Unix/Linux

在Unix/Linux操作系统上,你可以很容易的从源代友编译和安装扩展

Requirements

Prerequisite packages are:

  • PHP 5.x development resources
  • GCC compiler (Linux) or Xcode (Mac)
  • Git (if not already installed in your system - unless you download the package from GitHub and upload it on your server via FTP/SFTP)
#Ubuntu
sudo apt-get install php5-dev php5-mysql gcc
sudo apt-get install git-core

#Suse
yast2 -i php5-pear php5-dev php5-mysql gcc
yast2 -i git-core
Compilation

Creating the extension:

git clone git://github.com/phalcon/cphalcon.git
cd cphalcon/build
./install

(译者备注)./install其实是默认包含了phpize,configure,make,make install命令。如果您的机器中phpize,php-config不在环境命令中,请执行以下操作后再执行./install

ln -s phpdir/bin/phpize /usr/bin
ln -s phpdir/bin/php-cofnig /usr/bin

phpdir是你的php安装路径。

编辑php.ini文件,加入扩展

extension=phalcon.so

重启web server,如果是php-fpm,重启php-fpm即可

FreeBSD

A port is available for FreeBSD. Just only need these simple line commands to install it:

pkg_add -r phalcon

or

export CFLAGS="-O2 -fno-delete-null-pointer-checks"
cd /usr/ports/www/phalcon && make install clean
Installation Notes

Installation notes for Web Servers:

Apache Installation Notes

Apache is a popular and well known web server available on many platforms.

Configuring Apache for Phalcon

The following are potential configurations you can use to setup Apache with Phalcon. These notes are primarily focused on the configuration of the mod-rewrite module allowing to use friendly urls and the router component. Commonly an application has the following structure:

test/
  app/
    controllers/
    models/
    views/
  public/
    css/
    img/
    js/
    index.php
Directory under the main Document Root

This being the most common case, the application is installed in any directory under the document root. In this case, we use .htaccess 2 files, the first one to hide the application code and forward all requests to the application document root (public/).

# test/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule  ^$ public/    [L]
    RewriteRule  (.*) public/$1 [L]
</IfModule>

Now a second .htaccess file is located in the public/ directory, this re-writes all the URIs to the public/index.php file:

# test/public/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

If you do not want to use .htaccess files you can move these configurations to the apache’s main configuration file:

<IfModule mod_rewrite.c>

    <Directory "/var/www/test">
        RewriteEngine on
        RewriteRule  ^$ public/    [L]
        RewriteRule  (.*) public/$1 [L]
    </Directory>

    <Directory "/var/www/test/public">
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
    </Directory>

</IfModule>
Virtual Hosts

And this second configuration allow you to install a Phalcon application in a virtual host:

<VirtualHost *:80>

    ServerAdmin admin@example.host
    DocumentRoot "/var/vhosts/test/public"
    DirectoryIndex index.php
    ServerName example.host
    ServerAlias www.example.host

    <Directory "/var/vhosts/test/public">
        Options All
        AllowOverride All
        Allow from all
    </Directory>

</VirtualHost>
Nginx Installation Notes

Nginx is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Unlike traditional servers, Nginx doesn’t rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.

The PHP-FPM (FastCGI Process Manager) is usually used to allow Nginx to process PHP files. Nowadays, PHP-FPM is bundled with any Unix PHP distribution. Phalcon + Nginx + PHP-FPM provides a powerful set of tools that offer maximum performance for your PHP applications.

Configuring Nginx for Phalcon

The following are potential configurations you can use to setup nginx with Phalcon.

Dedicated Instance
server {
    listen       80;
    server_name  localhost;

    charset      utf-8;

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /srv/www/htdocs/phalcon-website/public;
        index  index.php index.html index.htm;

        # if file exists return it right away
        if (-f $request_filename) {
            break;
        }

        # otherwise rewrite it
        if (!-e $request_filename) {
            rewrite ^(.+)$ /index.php?_url=$1 last;
            break;
        }
    }

    location ~ \.php {
        # try_files    $uri =404;

        fastcgi_index  /index.php;
        fastcgi_pass   127.0.0.1:9000;

        include fastcgi_params;
        fastcgi_split_path_info       ^(.+\.php)(/.+)$;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
        root $root_path;
    }
}
Configuration by Host

And this second configuration allow you to have different configurations by host:

server {
    listen      80;
    server_name localhost;
    set         $root_path '/var/www/$host/public';
    root        $root_path;

    access_log  /var/log/nginx/$host-access.log;
    error_log   /var/log/nginx/$host-error.log error;

    index index.php index.html index.htm;

    try_files $uri $uri/ @rewrite;

    location @rewrite {
        rewrite ^/(.*)$ /index.php?_url=$1;
    }

    location ~ \.php {
        # try_files    $uri =404;

        fastcgi_index  /index.php;
        fastcgi_pass   127.0.0.1:9000;

        include fastcgi_params;
        fastcgi_split_path_info       ^(.+\.php)(/.+)$;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
        root $root_path;
    }

    location ~ /\.ht {
        deny all;
    }
}

教程 1: 让我们先来学习一个例子

在本节教程中,我们将带您创建一个简单的注册表单的应用程序。 我们还将解释框架的行为的基本方面。如果你有对自动生成部分代码感兴趣, 您可以查看 developer tools.

检查您的安装

我们假设你已经安装了Phalcon,您可以利用Phpinfo()函数来进行输出查看是否有phalcon出现?

<?php print_r(get_loaded_extensions()); ?>

如果在下面出现了phalcon扩展的字样,那么说明你安装成功了:

Array
(
    [0] => Core
    [1] => libxml
    [2] => filter
    [3] => SPL
    [4] => standard
    [5] => phalcon
    [6] => pdo_mysql
)

创建一个项目

学习的最好方法是,您按照本教程的指引一步一步的进行. 您可以从此处获得完整的代码 here.

目录结构

Phalcon 是松耦合的,因此并没有对文件的目录作固定,您可以根据您的需要或喜好,自定义文件目录结构

本教程的目的和出发点, 我们建议您使用以下类似的文件目录结构:

tutorial/
  app/
    controllers/
    models/
    views/
  public/
    css/
    img/
    js/

需要注意的是,您不需要包含任何类库到此项目中就可以工作了,因为Phalcon已经当作一个php模块加载进来了. (译者备注)比如您使用ZF或者其他框架的时候,你要么include进来,要么在include_path中加入框架的路径。但Phalcon却不必这样。

完美漂亮的URL

在本教程中,我们将教你如何做出漂亮的(友好的)网址。友好的URL非常有利于搜索引擎优化,因为它们很容易让用户记住。Phalcon支持最流行的Web服务器的重写。使您的应用程序的URL不完全依赖web server就可以写出很友好的格式。

在这个例子中,我们将使用为Apache重写模块。我们使用.htaccess文件的重写规则:

#/.htaccess
<IfModule mod_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 posing security threats.

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/.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>
Bootstrap

第一步,你需要创建一个程序的引导文件,这个文件是非常重要的,因为它作为您的应用程序的基础,让你控制它的各个方面,在这个文件中,你可以实现初始化组件以及应用程序的行为

一般我们会以index.php为引导程序的入口程序,public/index.php 内容大致如下:

<?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();

    //Setting up the view component
    $di->set('view', function(){
        $view = new \Phalcon\Mvc\View();
        $view->setViewsDir('../app/views/');
        return $view;
    });

    //Handle the request
    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);
    echo $application->handle()->getContent();

} catch(\Phalcon\Exception $e) {
     echo "PhalconException: ", $e->getMessage();
}
类的自动加载

在第一部分,我们发现注册了首先定义了一个autoloader,它的作用是用来自动加载应用中的控制类及模型类等。我们用它可以灵活的加载一个目录或者多个目录中的类。在下面的例子中,我们将介绍如何使用PhalconLoader

有了它,我们可以使用不同的策略来加载类库。下面的例子是自动注册控制器类目录及模型类目录:

<?php

$loader = new \Phalcon\Loader();
$loader->registerDirs(
    array(
        '../app/controllers/',
        '../app/models/'
    )
)->register();
依赖管理

使用Phalcon,你必须了解它的一个非常重要的概念,那就是他的依赖注入容器。听起来很复杂,但实际使用上它是非常简单和实用的。

译者注:学过或者对JAVA有些了解的人都应该十分熟悉依赖注入的概念,在早期这个概念被称作IOC(控制反转),后期才被称作DI。它们分别是inversion of control,Dependency Injection的英文缩写。只是DI更能表达其含意,因此后来基本都叫做DI。对这个概念不太懂的人,可以搜索一个这两个英文单词,相信你会有不少收获。

一个服务容器就相当于一个袋子,用于存储我们应用将要用到的一些服务,每当框架需要一个组件,将要求服务容器首先注册这个服务组件。Phalcon是一个高度松耦合的框架,PhalconDI 将使这些要用到的服务组件透明的结合在一起。

<?php

//Create a DI
$di = new Phalcon\DI\FactoryDefault();

Phalcon\DI\FactoryDefault 是PhalconDI的一个默认实现,为了使开发更容易,它注册了大量的服务组件集成到Phalcon。因此,我们不需要再一个一个的注册这些组件,以后直接使用也没有问题。

在接下来的部分,我们将注册一个“view”视图组件,并指定视图文件所在目录,由于视图不同于类文件,它们不能被autoloader自动加载。

服务组件可以通过多种方式进行注册,在我们的教程中,我们将使用lambda的匿名函数方式进行注册

<?php

//Setting up the view component
$di->set('view', function(){
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir('../app/views/');
    return $view;
});

在最后一部分,我们看到 Phalcon\Mvc\Application. 它的作用是初始化请求,对请求进行URL路由,分发响应,它收集所有的请求,执行并返回响应。

<?php

$application = new \Phalcon\Mvc\Application();
$application->setDI($di);
echo $application->handle()->getContent();

正如你所看到的,程序的引导文件是很短的,并且不需要加载任何额外的文件,我们定义的一个MVC应用代码可以少于30行代码。

创建一个控制器

默认情况下,Phalcon的控制器名默认为 “index”,这么做的原因是在请求中没有传递控制器及动作时,该控制器被自动调用(译者注:ZF等一些框架都是这么做的)默认的控制器(app/controllers/IndexController.php)大概是这个样子的:

<?php

class IndexController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {
        echo "<h1>Hello!</h1>";
    }

}

控制器的类名都必须以”Controller”结束,控制器类的方法名必须以”Action”结束,如果你通过浏览器访问应用,看到的是这个样子:

_images/tutorial-1.png

恭喜你,你的应用已经成功运行!

视图数据输出

通过控制器向视图输出数据有时候是必要的,但大多数情况下被证实不太理想。Phalcon是根据控制器和动作在视图目录中找到相应的视图文件的,看例子 (app/views/index/index.phtml):

<?php echo "<h1>Hello!</h1>";

控制器 (app/controllers/IndexController.php) 定义了一个空的动作,即(indexAction):

<?php

class IndexController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

}

不出意外的话,会输出 ‘hello world’.在执行action的时候,视图组件 Phalcon\Mvc\View 被自动创建。

设计一个注册表单

现在我们将修改 index.phtml 视图文件,同时添加一个新的控制器文件,并命名为”signup”.它的作用是让用户可以注册我们的应用。

<?php

echo "<h1>Hello!</h1>";

echo Phalcon\Tag::linkTo("signup", "Sign Up Here!");

以上代码会生成一个 html “A” 标签,连接到新的 signup 控制器上:

<h1>Hello!</h1> <a href="/test/signup">Sign Up Here!</a>

生成html标签,我们使用 Phalcon\Tag. 更多的html生成方式请查看 found here

_images/tutorial-2.png

下面是Signup控制器文件内容 (app/controllers/SignupController.php):

<?php

class SignupController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

}

The empty index action gives the clean pass to a view with the form definition: 视图文件内容 (app/views/sigup/index.phtml)

<?php use Phalcon\Tag; ?>

<h2>Sign using this form</h2>

<?php echo Tag::form("signup/register"); ?>

 <p>
    <label for="name">Name</label>
    <?php echo Tag::textField("name") ?>
 </p>

 <p>
    <label for="name">E-Mail</label>
    <?php echo Tag::textField("email") ?>
 </p>

 <p>
    <?php echo Tag::submitButton("Register") ?>
 </p>

</form>

通过浏览器访问,显示结果如下:

_images/tutorial-3.png

Phalcon\Tag 提供了很多的方法生成表章元素.

The Phalcon\Tag::form method receives only one parameter for instance, a relative uri to a controller/action in the application.

点击 “Send” 按钮时,你会发现Phalcon会抛出一个异常,表明我们在控制器中缺少”register” Action, public/index.php 抛出的异常内容如下:

PhalconException: Action “register” was not found on controller “signup”

实现registerAction后,异常消除:

<?php

class SignupController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function registerAction()
    {

    }

}

如果你点击”Send”按钮,将转到一个空白页面,表单中提交的name和email将存储到数据库,为了实现干净的面像对象,我们将使用models

Creating a Model

Phalcon带来了第一个用C语言写的PHP ORM,它简化了开发的复杂性。

在创建我们的第一个Model之前,我们需要把数据表映射到model,即我们需要先创建数据库及数据表结构,一个简单的用户表结构:

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(70) NOT NULL,
  `email` varchar(70) NOT NULL,
  PRIMARY KEY (`id`)
);

一个model需要放到 app/models目录下,下面定义的 Users model将映射到 “users”数据表上:

<?php

class Users extends \Phalcon\Mvc\Model
{

}
设置数据库连接

为了能够连接到数据库,并随后进行数据访问,通过我们创建的model,我们需要设定数据库连接。

数据库连接是另一种服务,我们的应用程序,由几部分组成:

<?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();

    //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/');
        return $view;
    });

    //Handle the request
    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);
    echo $application->handle()->getContent();

} catch(\Phalcon\Exception $e) {
     echo "PhalconException: ", $e->getMessage();
}

设置正确的数据库连接参数,我们创建的models才能正常工作。

使用models存储数据

接收由表单传过来的数据,并将他们存储到相应的数据表中

<?php

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 = $name;
        $user->email = $email;

        //Store and check for errors
        if ($user->save() == true) {
            echo "Thanks for register!";
        } else {
            echo "Sorry, the following problems were generated: ";
            foreach ($user->getMessages() as $message) {
                echo $message->getMessage(), "<br/>";
            }
        }
    }

}

用户提交的任何数据都是不可信的,因此我们需要对用户提交的数据进行过滤,只有通过验证和过滤后的内容,才进行保存。这使得应用程序更安全,因为这样避免了常见的攻击,比如SQL注入等

在本节教程中,我们使用过滤器过滤一个字符串类型的表单变量,以确保用户提交的内容不包含恶意字符, Phalcon\Filter 使得过滤任务不再复杂,因为我们可以直接使用request中的getPost调用

然后实际化Users类,它对应一个User,类的公共属性会映射到users数据表中的字段,通过调用save()方法把该条记录数据存储到数据表。save()方法返回一个 bool值,它告诉我们存储数据是否成功

译者注:save()方法是通过继承得来的,因为所有的Model都必须继承自 Phalcon\Mvc\Model。再注释一下,别太扣字眼,你当然也可以不继承自 Model,那么你就用不成model的相关功能了:)

其他的验证会自动发生,比如数据字段定义的not null,即类属性在保存时必须有值。如果我们不输入任何数据直接进行提交,将显示以下内容:

_images/tutorial-4.png

结束语

这是一个非常简单的教程,你可以看到,你可以使用Phalcon很容易的创建一个应用程序,希望您继续阅读本手册,这样你就可以发现Phalcon提供的更多的附加功能!

其他的示例

以下的示例也是使用Phalcon开发的,可以下载进行学习。同时欢迎提供更多的完整的示例程序:

教程 2: 解读分析 INVO 项目

在第二个教程中,我们将解读分析一个更完整的应用程序,以强化你对Phalcon的理解,INVO是我们已经创建了的作为示例程序的应用程序之一。你可以从 Github 获得INVO的全部代码。

此外还需要说明的是,INVO的html实现是使用 Twitter Bootstrap CSS framework来完成的,在这个示例项目中,并不真正的生成发票(这是一个类似于进销存的相关的应用),但它作为一个例子还是可以告诉你整个框架是如何工作的。

项目目录结构

从Github上克隆了源代码后,你可以发现目录结构是这样的:

invo/
    app/
        app/config/
        app/controllers/
        app/library/
        app/models/
        app/plugins/
        app/views/
    public/
        public/bootstrap/
        public/css/
        public/js/
    schemas/

在前面的章节已经讲过,Phalcon并没有固定的目录结构,该项目提供了一个简单的MVC目录结构。

通过浏览器打开应用程序 http://localhost/invo 显示效果如下:

_images/invo-1.png

INVO应用程序分为两部分,即通常我们说的前台后台。前台部分,用户可以通过INVO查看一些信息,同时可以提交联系方式。后台部分,相当于管理区域,在这里面注册用户可以管理自己的产品和客户。

标准路由器

INVO使用标准的内奸路由器组件,此路由的匹配模式如下 /:controller/:action/:params ,这意味着,URL中的第一部分是控制器,第二个是action方法。

路由 /session/register 将要执行SessionController中的RegisterAction方法

Configuration

INVO有一个配置文件,用于设置一些常用的数据,比如数据库连接参数,目录结构等。在引导文件 (public/index.php) 的第一部分,可以这样读取配置文件

<?php

//Read the configuration
$config = new Phalcon\Config\Adapter\Ini(__DIR__.'/../app/config/config.ini');

Phalcon\Config 使得读取配置内容是面像对象的,配置文件的定义如下:

[database]
host     = localhost
username = root
password = secret
name     = invo

[application]
controllersDir = /../app/controllers/
modelsDir      = /../app/models/
viewsDir       = /../app/views/
pluginsDir     = /../app/plugins/
libraryDir     = /../app/library/
baseUri        = /invo/

;[metadata]
;adapter = "Apc"
;suffix = my-suffix
;lifetime = 3600

Phalcon的配置文件可以分类进行定义,在这个文件中,共定义了三个部分 database,application,metadata

Autoloaders

在引导文件 (public/index.php) 的第二部分是autoloader,autoloader注册了一些目录,在这些目录中放置的是我们应用程序需要用到的类文件

<?php

$loader = new \Phalcon\Loader();

$loader->registerDirs(
    array(
        __DIR__.$config->application->controllersDir,
        __DIR__.$config->application->pluginsDir,
        __DIR__.$config->application->libraryDir,
        __DIR__.$config->application->modelsDir,
    )
)->register();

需要注意的是,注册的这些目录并不包括 viewsDir,因为viewsDir中并不包含classes文件,而是html+php文件

处理请求

在引导文件的最后部分,我们使用 Phalcon\Mvc\Application ,这个类初始化并执行用户的请求

<?php

$application = new \Phalcon\Mvc\Application();
$application->setDI($di);
echo $application->handle()->getContent();

依赖注入

看上面代码中的第二段,变量$application通过setDI()方法接收了变量$di,该变量的目的是什么呢?

Phalcon是一个松耦合的框架,所以我们需要一个组件,把它们整合到一起,让它们一起工作,该组件便是 Phalcon\DI

注册到容器的方法有很多,在INVO中,大都采用匿名函数的方式进行注册,因为此种方式是lazy load的加载方式,减少了应用程序请求资源控制。

例如,在下面的代码片断中的session会话服务,采用的是匿名函数的方式进行注册的,因此当使用session的时候,才会被加载。

<?php

//Start the session the first time when some component request the session service
$di->set('session', function(){
    $session = new Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});

在这里,我们可以自由的更改适配器,以使它执行更多的初始化任务,请注意,服务注册的”session”请不要随意修改,这是一个命名约定。

译者注:更多的服务组件命名约定可见 dependency injection container

一个请求可能使用多个服务组件,一个一个的注册这些组件是一项繁重的任务,出于这个原因,该框架提供了 Phalcon\DI 的一个实现,就是 Phalcon\DI\FactoryDefault

译者注:其实 Phalcon\DI\FactoryDefault 就是 Phalcon\DI 的一个子类

<?php

// The FactoryDefault Dependency Injector automatically registers the
// right services providing a full stack framework
$di = new \Phalcon\DI\FactoryDefault();

It registers the majority of services with components provided by the framework as standard. If we need to override the definition of some it could be done as above with “session”. Now we know the origin of the variable $di.

大多数的服务组件都由框架本身提供,如果我们需要覆盖一些定义的话,比如”session”.(翻译的可能不对,英文部分就不去掉了)

Log into the Application

登录将使用后端控制器,控制器前后端分离是合乎逻辑的,所有的控制器被放置到相同的目录中。要登录系统,我们必须有一个有效的用户名和密码,用户信息被存储在数据库”invo”的”users”数据表中。

在我们登录系统之前,我们需要在应用程序中配置数据库连接。一个命名为”db”的服务组件被注册,与autoloader相同,我们也从配置文件中读取相关配置连接参数

<?php

// Database connection is created based in the parameters defined in the configuration file
$di->set('db', function() use ($config) {
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => $config->database->host,
        "username" => $config->database->username,
        "password" => $config->database->password,
        "dbname" => $config->database->name
    ));
});

这时,会返回一个MySQL的连接适配器的实例,如果需要的话,你可以做一些其他额外的操作,例如,你还可以定义一个记录器,分析器或更改为其他适配器。或者设置你想要的其他东西

那么,下面的这个表单示例 (app/views/session/index.phtml) 是一个登录入口,已经删除了一些HTML代码,使这个例子更简洁:

<?php echo Tag::form('session/start') ?>

    <label for="email">Username/Email</label>
    <?php echo Tag::textField(array("email", "size" => "30")) ?>

    <label for="password">Password</label>
    <?php echo Tag::passwordField(array("password", "size" => "30")) ?>

    <?php echo Tag::submitButton(array('Login')) ?>

</form>

SessionController::startAction (app/controllers/SessionController.phtml) 验证用户登录,通过查询数据库的用户的登录名称和密码是否正确

<?php

class SessionController extends ControllerBase
{

    // ...

    private function _registerSession($user)
    {
        $this->session->set('auth', array(
            'id' => $user->id,
            'name' => $user->name
        ));
    }

    public function startAction()
    {
        if ($this->request->isPost()) {

            //Taking the variables sent by POST
            $email = $this->request->getPost('email', 'email');
            $password = $this->request->getPost('password');

            $password = sha1($password);

            //Find for the user in the database
            $user = Users::findFirst("email='$email' AND password='$password' AND active='Y'");
            if ($user != false) {

                $this->_registerSession($user);

                $this->flash->success('Welcome '.$user->name);

                //Forward to the invoices controller if the user is valid
                return $this->dispatcher->forward(array(
                    'controller' => 'invoices',
                    'action' => 'index'
                ));
            }

            $this->flash->error('Wrong email/password');
        }

        //Forward to the login form again
        return $this->dispatcher->forward(array(
            'controller' => 'session',
            'action' => 'index'
        ));

    }

}

需要注意的是控制器中有多个公共属性,如$this->flash,$this->request,$this->session。这些属性在引导文件中使用 Phalcon\DI 注册的,如果你仔细看过前面的章节,应该能想到。因此可以在控制器中直接使用他们

这些服务是共享的,这意味着我们访问的是相同的实例,无论我们在任何地方调用它们。

举个例子,在这里我们可以直接调用 “session”, 同时把用户的信息存储到变量auth中

<?php

$this->session->set('auth', array(
    'id' => $user->id,
    'name' => $user->name
));

Securing the Backend

后端是一个私有区域,只有注册的用户才可以访问。因此,它必须进行检查验证,只有注册用户才可以访问这些控制器。如果你没有登录应用程序,你尝试访问的时候,你会看到这样的界面:

_images/invo-2.png

每当有人试图访问任何控制器和动作,应用程序就会验证当前用户的角色是否能够访问,否则会显示一个信息,同时跳转到首页面。

现在,我们来看看应用程序如何实现这一点。首先要知道的是,有一个组件叫分发器(Dispatcher),你还需要了解一个路由。在此基础上,负载加载相应的控制器和执行相应的动作。

通常情况下,框架会自动创建分发器,在这个例子中,我们要专门创建一个动作,显示出用户成功访问和不成功访问的情况。为了实现这一目标,我们更在引导文件(bootstrap)中创建一个函数:

<?php

$di->set('dispatcher', function() use ($di) {
    $dispatcher = new Phalcon\Mvc\Dispatcher();
    return $dispatcher;
});

现在,我们的应用程序中就有了控制分发器,现实中,我们需要修改框架中有许多组件的内部流程,这时一个新的组件EventsManager出来了,它可以提供在组件中加入一些其他对像。

译者注:如在分发器中加入验证,在数据库连接中加入记录器等

事件管理

一个事件管理器,可以让我们针听一个特定类型的事件,下面看一下在分发器中加入安全验证的例子:

<?php

$di->set('dispatcher', function() use ($di) {

    //Obtain the standard eventsManager from the DI
    $eventsManager = $di->getShared('eventsManager');

    //Instantiate the Security plugin
    $security = new Security($di);

    //Listen for events produced in the dispatcher using the Security plugin
    $eventsManager->attach('dispatch', $security);

    $dispatcher = new Phalcon\Mvc\Dispatcher();

    //Bind the EventsManager to the Dispatcher
    $dispatcher->setEventsManager($eventsManager);

    return $dispatcher;
});

安全插件是一个类文件(app/plugins/Security.php),这个类实现了”beforeExecuteRoute”方法.

译者注:都可以实现哪些方法,可以查看 分发器 Dispatch Loop Events 部分

<?php

use \Phalcon\Events\Event;
use \Phalcon\Mvc\Dispatcher;

class Security extends Phalcon\Mvc\User\Plugin
{

    // ...

    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        // ...
    }

}

插件程序接收两个参数,第一个参数是event上下文信息,第二个是事件管理器要管理的对象,插件程序并不一定非得继承自 Phalcon\Mvc\User\Plugin ,但如果这样继承了,他们更容易的访问应用程序的其他服务组件。

译者注:目前的 Phalcon\Mvc\User\Plugin 以及 Phalcon\Mvc\User\Component 是一样的,其实两者的侧重点应该是不同的,只是作者还未完善而已。具体请看stackoverflow的贴子

http://stackoverflow.com/questions/12879284/whats-different-between-phalcon-mvc-user-component-and-phalcon-mvc-user-plugin

现在,我们验证登录用户的权限,看他的权限是否在ACL列表中,如果没有(也就是说没有权限的话),分发器将使流程跳转到主页:

<?php

use \Phalcon\Events\Event;
use \Phalcon\Mvc\Dispatcher;

class Security extends Phalcon\Mvc\User\Plugin
{

    // ...

    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {

        //Check whether the "auth" variable exists in session to define the active role
        $auth = $this->session->get('auth');
        if (!$auth) {
            $role = 'Guests';
        } else {
            $role = 'Users';
        }

        //Take the active controller/action from the dispatcher
        $controller = $dispatcher->getControllerName();
        $action = $dispatcher->getActionName();

        //Obtain the ACL list
        $acl = $this->_getAcl();

        //Check if the Role have access to the controller (resource)
        $allowed = $acl->isAllowed($role, $controller, $action);
        if ($allowed != Phalcon\Acl::ALLOW) {

            //If he doesn't have access forward him to the index controller
            $this->flash->error("You don't have access to this module");
            $dispatcher->forward(
                array(
                    'controller' => 'index',
                    'action' => 'index'
                )
            );

            //Returning "false" we tell to the dispatcher to stop the current operation
            return false;
        }

    }

}
Providing an ACL list

权限管理部分,我一般不太喜欢使用这种方式的权限验证,不过大多数框架都提供了这种验证,包括ZF。

In the previous example we obtain the ACL using the method $this->_getAcl(). This method is also implemented in the Plugin. Now explain step by step how we built the access control list:

<?php

//Create the ACL
$acl = new Phalcon\Acl\Adapter\Memory();

//The default action is DENY access
$acl->setDefaultAction(Phalcon\Acl::DENY);

//Register two roles, Users is registered users
//and guests are users without a defined identity
$roles = array(
    'users' => new Phalcon\Acl\Role('Users'),
    'guests' => new Phalcon\Acl\Role('Guests')
);
foreach($roles as $role){
    $acl->addRole($role);
}

Now we define the respective resources of each area. Controller names are resources and their actions are the accesses in the resources:

<?php

//Private area resources (backend)
$privateResources = array(
    'companies' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'),
    'products' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'),
    'producttypes' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'),
    'invoices' => array('index', 'profile')
);
foreach($privateResources as $resource => $actions){
    $acl->addResource(new Phalcon\Acl\Resource($resource), $actions);
}

//Public area resources (frontend)
$publicResources = array(
    'index' => array('index'),
    'about' => array('index'),
    'session' => array('index', 'register', 'start', 'end'),
    'contact' => array('index', 'send')
);
foreach($publicResources as $resource => $actions){
    $acl->addResource(new Phalcon\Acl\Resource($resource), $actions);
}

The ACL now have knowledge of the existing controllers and their related actions. The role “Users” has access to all the resources of both the frontend and the backend. The role “Guests” only have access to the public area:

<?php

//Grant access to public areas to both users and guests
foreach ($roles as $role) {
    foreach ($publicResources as $resource => $actions) {
        $acl->allow($role->getName(), $resource, '*');
    }
}

//Grant access to private area only to role Users
foreach ($privateResources as $resource => $actions) {
    foreach ($actions as $action) {
        $acl->allow('Users', $resource, $action);
    }
}

Hooray!, the ACL is now complete.

用户自定义组件

本应用所有的UI组件和显示风格都是使用的Twitter的CSS Framework。

这部分被实现使用成Component (api/library/Elements.php)。

译者注:在上面讲Plugins的时候,专门介绍了Component,没注意的可以往上看一下。

<?php

class Elements extends Phalcon\Mvc\User\Component
{

    public function getMenu()
    {
        //...
    }

    public function getTabs()
    {
        //...
    }

}

这个类继承自 Phalcon\Mvc\User\Component,虽然框架本身不强制要求继承,但如果你继承了它,将更方便的访问应用程序中的其他组件。现在,我们把它注入到容器中:

<?php

//Register an user component
$di->set('elements', function(){
    return new Elements();
});

在控制器中以及视图中,插件以及组件可以通过注册的名称很方便的被调用

<div class="navbar navbar-fixed-top">
    <div class="navbar-inner">
        <div class="container">
            <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </a>
            <a class="brand" href="#">INVO</a>
            <?php echo $this->elements->getMenu() ?>
        </div>
    </div>
</div>

<div class="container">
    <?php echo $this->getContent() ?>
    <hr>
    <footer>
        <p>&copy; Company 2012</p>
    </footer>
</div>

重点看这句:

<?php echo $this->elements->getMenu() ?>

增删查改

大多数菜单选项数据(如公司,产品,产品类型等),我们开发按照普遍的 CRUD (Create, Read, Update and Delete)方式,每个CURD包含以下文件:

invo/
    app/
        app/controllers/
            ProductsController.php
        app/models/
            Products.php
        app/views/
            products/
                edit.phtml
                index.phtml
                new.phtml
                search.phtml

每个控制器包含以下一些动作(控制器类中的方法):

译者注:这些动作名称并不是约定的,可以按你的喜好自由修改,比如searchAction,你可以写成soAction都没问题。但请求的时候就不再请求到products/search了,而是需要请求到products/so

<?php

class ProductsController extends ControllerBase
{

    /**
     * The start action, it shows the "search" view
     */
    public function indexAction()
    {
        //...
    }

    /**
     * Execute the "search" based on the criteria sent from the "index"
     * Returning a paginator for the results
     */
    public function searchAction()
    {
        //...
    }

    /**
     * Shows the view to create a "new" product
     */
    public function newAction()
    {
        //...
    }

    /**
     * Shows the view to "edit" an existing product
     */
    public function editAction()
    {
        //...
    }

    /**
     * Creates a product based on the data entered in the "new" action
     */
    public function createAction()
    {
        //...
    }

    /**
     * Updates a product based on the data entered in the "edit" action
     */
    public function saveAction()
    {
        //...
    }

    /**
     * Deletes an existing product
     */
    public function deleteAction($id)
    {
        //...
    }

}
检索表单

检索表单显示了数据表(products)中的所有可查询的字段,允许用户根据自定义检索内容。

数据表”products”,关联了数据表”products_types”,在这种情况下,我们在检索页面这样写:

<?php

/**
 * The start action, it shows the "search" view
 */
public function indexAction()
{
    $this->persistent->searchParams = null;
    $this->view->setVar("productTypes", ProductTypes::find());
}

所有”product types”将通过变量”productTypes”显示到视图文件中,视图文件(app/views/index.phtml)的代码如下:

<?php

<div>
    <label for="product_types_id">Product Type</label>
    <?php echo Tag::select(array(
        "product_types_id",
        $productTypes,
        "using" => array("id", "name"),
        "useDummy" => true
    )) ?>
</div>

变量$productTypes包含的数据通过 Phalcon\Tag::select 填充到视图进行显示。一旦提交检索表单,它会请求到 products/search,并根据用户提交的数据进行数据检索

执行一个检索

“search”,即products/search 这个动作具有双重行为,当通过POST访问时,它会根据用户提交的数据进行条件检索。但是,当我们通过GET访问时,将显示所有产品的列表。这些都是通过HTTP方法来进行区分的。详情请查看 Request component:

<?php

/**
 * Execute the "search" based on the criteria sent from the "index"
 * Returning a paginator for the results
 */
public function searchAction()
{

    if ($this->request->isPost()) {
        //create the query conditions
    } else {
        //paginate using the existing conditions
    }

    //...

}

使用 Phalcon\Mvc\Model\Criteria ,我们可以很方便的把表单提交的数据(值)和数据类型(属性或字段)绑定到一起

<?php

$query = Criteria::fromInput($this->di, "Products", $_POST);

该方法的绑定过程是这样的,首先验证客户端提交的表单数据是否为空”“(空字符串),如果不是,将绑定到数据字段上。如果提交的表单数据是字符串类型的(CHAR, VARCHAR, TEXT等),将使用 “like ‘%%’”这样的形式来进行检索数据。如果不是或不类似于字符串,它会直接使用操作符”=”进行检索。

此外,如果提交的数据中不包括在数据表字段(也可以说成是model字段)中,这些数据将被忽略。此外,提交的数据会自动使用bound parameter的方式进行绑定。

我们把提交的绑定数据存储到session中,此处使用的是 Session Bag

<?php

$this->persistent->searchParams = $query->getParams();

Session Bag是一个特殊的属性,它存在于控制器中。这个属性注入的其实是 Phalcon\Session\Bag 组件。

译者注:经测试,使用 $this->persistent->xxx,只能在同一控制器中的不同Action中进行访问,不能在其他控制器中访问到数据。如果需要在不同的控制器访问到变量xxx的数据,可以使用session

封装绑定好数据后,我们通过这个参数来进行数据检索:

<?php

$products = Products::find($parameters);
if (count($products) == 0) {
    $this->flash->notice("The search did not found any products");
    return $this->forward("products/index");
}

如果检索不到任何产品,将跳转到 products/index 页面。否则,读取检索到的数据,进行分页显示:

<?php

$paginator = new Phalcon\Paginator\Adapter\Model(array(
    "data" => $products,    //Data to paginate
    "limit" => 5,           //Rows per page
    "page" => $numberPage   //Active page
));

//Get active page in the paginator
$page = $paginator->getPaginate();

最后,把分页的数据绑定到视图上。即把变量$page绑定到视图的page上:

<?php

$this->view->setVar("page", $page);

在视图文件(app/views/products/search.phtml) 中,我们这样进行数据显示:

<?php foreach($page->items as $product){ ?>
    <tr>
        <td><?= $product->id ?></td>
        <td><?= $product->getProductTypes()->name ?></td>
        <td><?= $product->name ?></td>
        <td><?= $product->price ?></td>
        <td><?= $product->active ?></td>
        <td><?= Tag::linkTo("products/edit/".$product->id, 'Edit') ?></td>
        <td><?= Tag::linkTo("products/delete/".$product->id, 'Delete') ?></td>
    </tr>
<?php } ?>
创建以及更新一条数据记录

现在,让我们来看看如何使用CURD创建和更新一个记录。通过控制器的”new”和”edit”两个Action,我们可以提交数据输入。他们分别能过”create”和”save”两个Action来保存提交的数据。

译者注:说白了就是 newAction就是新建产品页面,点击右上角的Save按钮保存时,会调用createAction。同理....

在创建的情况下,我们把用户提交的数据和”products”这个产品实例进行绑定。

译者注:即把用户提交的数据通过绑定到model上,以实现保存到数据库的目的。

<?php

/**
 * Creates a product based on the data entered in the "new" action
 */
public function createAction()
{

    $products = new Products();
    $products->id = $request->getPost("id", "int");
    $products->product_types_id = $request->getPost("product_types_id", "int");
    $products->name = $request->getPost("name", "striptags");
    $products->price = $request->getPost("price", "double");
    $products->active = $request->getPost("active");

    //...

}

提交的数据被过滤,然后再赋值到对象的属性,保存时,我们就可以知道用户提交的数据有没有符合业务规则。同时,可以在 Products Model中实现验证。

<?php

/**
 * Creates a product based on the data entered in the "new" action
 */
public function createAction()
{

    //...

    if (!$products->save()) {

        //The store failed, the following messages were produced
        foreach ($products->getMessages() as $message) {
            $this->flash->error((string) $message);
        }
        return $this->forward("products/new");

    } else {
        $this->flash->success("Product was created successfully");
        return $this->forward("products/index");
    }

}

现在来说产品编辑部分,首先得保证数据库中有可编辑的数据:

<?php

/**
 * Shows the view to "edit" an existing product
 */
public function editAction($id)
{

    //...

    $product = Products::findFirst("id = '$id'");

    Tag::displayTo("id", $product->id);
    Tag::displayTo("product_types_id", $product->product_types_id);
    Tag::displayTo("name", $product->name);
    Tag::displayTo("price", $product->price);
    Tag::displayTo("active", $product->active);

}

通过 displayTo helper设置从数据库中取得的数据到页面,然后用户可以更改这些数据,然后再通过saveAction保存到数据库。

<?php

/**
 * Updates a product based on the data entered in the "edit" action
 */
public function saveAction()
{

    //...

    //Find the product to update
    $id = $request->getPost("id", "int");
    $products = Products::findFirst("id='$id'");
    if ($products == false) {
        $this->flash->error("products does not exist ".$id);
        return $this->forward("products/index");
    }

    //... assign the values to the object and store it

}

动态更改标题

当你浏览不同的控制器及动作时,网页标题会不同,如果更改标题呢,可以在每个控制器进行初始化:

<?php

class ProductsController extends ControllerBase
{

    public function initialize()
    {
        //Set the document title
        Tag::setTitle('Manage your product types');
        parent::initialize();
    }

    //...

}

注意,上面的方法中调用了 parent::initialize() ,你可以在 parent::initialize() 方法中加入更多的内容到标题:

<?php

class ControllerBase extends Phalcon\Mvc\Controller
{

    protected function initialize()
    {
        //Prepend the application name to the title
        Phalcon\Tag::prependTitle('INVO | ');
    }

    //...
}

最后,我们在视图文件 (app/views/index.phtml) 中这样获得标题:

<?php use Phalcon\Tag as Tag ?>
<!DOCTYPE html>
<html>
    <head>
        <?php echo Tag::getTitle() ?>
    </head>
    <!-- ... -->
</html>

结束语

本教程从各个方面讲解了如何使用Phalcon来创建一个应用程序,希望你也能提供示例程序,同时学习更多的内容。

教程 3: 创建 RESTful风格 API

在本节教程中,我们将展示如何使用不同的HTTP方法创建一个简单的 RESTful 风格的API。

  • 使用HTTP GET方法获取以及检索数据
  • 使用HTTP POST方法添加数据
  • 使用HTTP PUT方法更新数据
  • 使用HTTP DELETE方法删除数据

Defining the API

API包括以下方法:

Method URL Action
GET /api/robots Retrieves all robots
GET /api/robots/search/Astro Searches for robots with ‘Astro’ in their name
GET /api/robots/2 Retrieves robots based on primary key
POST /api/robots Adds a new robot
PUT /api/robots/2 Updates robots based on primary key
DELETE /api/robots/2 Deletes robots based on primary key

创建应用

RESTful风格的应用程序非常简单,我们用不着使用完整的MVC环境来开发它。在这种情况下,我们只要使用 micro application 就可以了。

下面的文件结构足够了:

my-rest-api/
    models/
        Robots.php
    index.php
    .htaccess

首先,我们需要创建一个.htaccess的文件,包含index.php文件的全部重写规则,下面示例就是此文件的全部:

译者注:使用.htaccess文件,前提是指定了你使用的是Apache WEB Sever.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

然后,我们按以下方式创建 index.php 文件:

<?php

$app = new \Phalcon\Mvc\Micro();

//define the routes here

$app->handle();

现在,我们按我们上面的定义创建路由规则:

<?php

$app = new Phalcon\Mvc\Micro();

//Retrieves all robots
$app->get('/api/robots', function() {

});

//Searches for robots with $name in their name
$app->get('/api/robots/search/{name}', function($name) {

});

//Retrieves robots based on primary key
$app->get('/api/robots/{id:[0-9]+}', function($id) {

});

//Adds a new robot
$app->post('/api/robots', function() {

});

//Updates robots based on primary key
$app->put('/api/robots/{id:[0-9]+}', function() {

});

//Deletes robots based on primary key
$app->delete('/api/robots/{id:[0-9]+}', function() {

});

$app->handle();

每个API方法都需要定义一个与定义的HTTP方法相同名称的路由规则,第一个参数传递路由规则,第二个是处理程序,在这种情况下,处理程序是一个匿名函数。路由规则 ‘/api/robots/{id:[0-9]+}’,明确设置’id’参数必须是一个数字。

当用户请求匹配上已定义的路由时,应用程序将执行相应的处理程序。

创建模型(Model)

API需要提供robots的相关信息,这些数据都存储在数据库中。下面的模型使我们以一种面向对象的方式访问数据表。我们需要使用内置的验证器实现一些业务规则。这样做,会使我们对数据更安全的存储放心,以达到我们想要实现的目的:

<?php

use \Phalcon\Mvc\Model\Message;
use \Phalcon\Mvc\Model\Validator\InclusionIn;
use \Phalcon\Mvc\Model\Validator\Uniqueness;

class Robots extends \Phalcon\Mvc\Model
{

    public function validation()
    {
        //Type must be: droid, mechanical or virtual
        $this->validate(new InclusionIn(
            array(
                "field"  => "type",
                "domain" => array("droid", "mechanical", "virtual")
            )
        ));

        //Robot name must be unique
        $this->validate(new Uniqueness(
            array(
                "field"   => "name",
                "message" => "The robot name must be unique"
            )
        ));

        //Year cannot be less than zero
        if ($this->year < 0) {
            $this->appendMessage(new Message("The year cannot be less than zero"));
        }

        //Check if any messages have been produced
        if ($this->validationHasFailed() == true) {
            return false;
        }
    }

}

现在,我们来创建数据库连接以便使用这个模型:

<?php

$di = new \Phalcon\DI\FactoryDefault();

//Set up the database service
$di->set('db', function(){
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "asimov",
        "password" => "zeroth",
        "dbname" => "robotics"
    ));
});

$app = new \Phalcon\Mvc\Micro();

//Bind the DI to the application
$app->setDI($di);

获取数据

第一个”handler”实现通过HTTP GET获取所有可用的robots。让我们使用PHQL执行一个简单的数据查询,并返回JSON数据格式:

<?php

//Retrieves all robots
$app->get('/api/robots', function() use ($app) {

    $phql = "SELECT * FROM Robots ORDER BY name";
    $robots = $app->modelsManager->executeQuery($phql);

    $data = array();
    foreach($robots as $robot){
        $data[] = array(
            'id' => $robot->id,
            'name' => $robot->name,
        );
    }

    echo json_encode($data);

});

PHQL,根据我们使用的数据库系统,允许我们使用面向对象的SQL方言,在内部将其转化为普通的SQL语言,此例使用”use”关键词的匿名函数,允许从整体到局部传递变量。

译者注:不了解匿名函数及use语法的,请查看PHP 5.4版本的文档(具体是5.3开始,还是5.4开始我也不太清楚,就不查证了)。

处理程序看起来像这样:

<?php

//Searches for robots with $name in their name
$app->get('/api/robots/search/{name}', function($name) use ($app) {

    $phql = "SELECT * FROM Robots WHERE name LIKE :name: ORDER BY name";
    $robots = $app->modelsManager->executeQuery($phql, array(
        'name' => '%'.$name.'%'
    ));

    $data = array();
    foreach($robots as $robot){
        $data[] = array(
            'id' => $robot->id,
            'name' => $robot->name,
        );
    }

    echo json_encode($data);

});

通过字段”id”检索与上例相当类似,在这种情况下,如果没有检索到,会提示未找到。

<?php

//Retrieves robots based on primary key
$app->get('/api/robots/{id:[0-9]+}', function($id) use ($app) {

    $phql = "SELECT * FROM Robots WHERE id = :id:";
    $robot = $app->modelsManager->executeQuery($phql, array(
        'id' => $id
    ))->getFirst();

    if ($robot==false) {
        $response = array('status' => 'NOT-FOUND');
    } else {
        $response = array(
            'status' => 'FOUND',
            'data' => array(
                'id' => $robot->id,
                'name' => $robot->name
            )
        );
    }

    echo json_encode($response);
});

插入数据

客户端提交JSON包装的字符串,我们也使用PHQL插入:

<?php

//Adds a new robot
$app->post('/api/robots', function() use ($app) {

    $robot = json_decode($app->request->getRawBody());

    $phql = "INSERT INTO Robots (name, type, year) VALUES (:name:, :type:, :year:)";

    $status = $app->modelsManager->executeQuery($phql, array(
        'name' => $robot->name,
        'type' => $robot->type,
        'year' => $robot->year
    ));

    //Check if the insertion was successfull
    if($status->success()==true){

        $robot->id = $status->getModel()->id;

        $response = array('status' => 'OK', 'data' => $robot);

    } else {

        //Change the HTTP status
        $this->response->setStatusCode(500, "Internal Error")->sendHeaders();

        //Send errors to the client
        $errors = array();
        foreach ($status->getMessages() as $message) {
            $errors[] = $message->getMessage();
        }

        $response = array('status' => 'ERROR', 'messages' => $errors);

    }

    echo json_encode($response);

});

更新数据

更新数据非常类似于插入数据。传递的”id”参数指明哪个robots将被更新:

<?php

//Updates robots based on primary key
$app->put('/api/robots/{id:[0-9]+}', function($id) use($app) {

    $robot = json_decode($app->request->getRawBody());

    $phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:";
    $status = $app->modelsManager->executeQuery($phql, array(
        'id' => $id,
        'name' => $robot->name,
        'type' => $robot->type,
        'year' => $robot->year
    ));

    //Check if the insertion was successfull
    if($status->success()==true){

        $response = array('status' => 'OK');

    } else {

        //Change the HTTP status
        $this->response->setStatusCode(500, "Internal Error")->sendHeaders();

        $errors = array();
        foreach ($status->getMessages() as $message) {
            $errors[] = $message->getMessage();
        }

        $response = array('status' => 'ERROR', 'messages' => $errors);

    }

    echo json_encode($response);

});

删除数据

删除数据非常类似于更新数据。传递的”id”参数指明哪个robot被删除:

<?php

//Deletes robots based on primary key
$app->delete('/api/robots/{id:[0-9]+}', function($id) use ($app) {

    $phql = "DELETE FROM Robots WHERE id = :id:";
    $status = $app->modelsManager->executeQuery($phql, array(
        'id' => $id
    ));
    if($status->success()==true){

        $response = array('status' => 'OK');

    } else {

        //Change the HTTP status
        $this->response->setStatusCode(500, "Internal Error")->sendHeaders();

        $errors = array();
        foreach ($status->getMessages() as $message) {
            $errors[] = $message->getMessage();
        }

        $response = array('status' => 'ERROR', 'messages' => $errors);

    }

    echo json_encode($response);

});

测试应用

使用 curl 可以测试应用程序中每个操作的正确性:

获取所有robots:

curl -i -X GET http://localhost/my-rest-api/api/robots

HTTP/1.1 200 OK
Date: Wed, 12 Sep 2012 07:05:13 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 117
Content-Type: text/html; charset=UTF-8

[{"id":"1","name":"Robotina"},{"id":"2","name":"Astro Boy"},{"id":"3","name":"Terminator"}]

通过名称查找robot:

curl -i -X GET http://localhost/my-rest-api/api/robots/search/Astro

HTTP/1.1 200 OK
Date: Wed, 12 Sep 2012 07:09:23 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 31
Content-Type: text/html; charset=UTF-8

[{"id":"2","name":"Astro Boy"}]

通过 id 查找 robot:

curl -i -X GET http://localhost/my-rest-api/api/robots/3

HTTP/1.1 200 OK
Date: Wed, 12 Sep 2012 07:12:18 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 56
Content-Type: text/html; charset=UTF-8

{"status":"FOUND","data":{"id":"3","name":"Terminator"}}

插入一个新的robot:

curl -i -X POST -d '{"name":"C-3PO","type":"droid","year":1977}'
    http://localhost/my-rest-api/api/robots

HTTP/1.1 200 OK
Date: Wed, 12 Sep 2012 07:15:09 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 75
Content-Type: text/html; charset=UTF-8

{"status":"OK","data":{"name":"C-3PO","type":"droid","year":1977,"id":"4"}}

尝试插入一个与存在的robot相同名称的robot:

curl -i -X POST -d '{"name":"C-3PO","type":"droid","year":1977}'
    http://localhost/my-rest-api/api/robots

HTTP/1.1 500 Internal Error
Date: Wed, 12 Sep 2012 07:18:28 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 63
Content-Type: text/html; charset=UTF-8

{"status":"ERROR","messages":["The robot name must be unique"]}

或者使用错误的type值更新一个robot:

curl -i -X PUT -d '{"name":"ASIMO","type":"humanoid","year":2000}'
    http://localhost/my-rest-api/api/robots/4

HTTP/1.1 500 Internal Error
Date: Wed, 12 Sep 2012 08:48:01 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 104
Content-Type: text/html; charset=UTF-8

{"status":"ERROR","messages":["Value of field 'type' must be part of
    list: droid, mechanical, virtual"]}

最后,测试删除一个robot数据:

curl -i -X DELETE http://localhost/my-rest-api/api/robots/4

HTTP/1.1 200 OK
Date: Wed, 12 Sep 2012 08:49:29 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 15
Content-Type: text/html; charset=UTF-8

{"status":"OK"}

结论

正如你所看到的那样,使用Phalcon开发RESTful风格的API相当容易。在接下来的文档中,我们会具体讲解如何开发微应用(micro applications)以及如何使用 PHQL

使用依赖注入

下面要讲的这个例子有点长,但可以很好的解释为什么使用Service Container以及DI。首先,我们假设,我们要开发一个组件命名为SomeComponent。这个组件中现在将要注入一个数据库连接。

在这个例子中,数据库连接在component中被创建,这种方法是不切实际的,这样做的话,我们将不能改变数据库连接参数及数据库类型等一些参数。

<?php

class SomeComponent
{

    /**
     * The instantiation of the connection is hardcoded inside
     * the component so is difficult to replace it externally
     * or change its behavior
     */
    public function someDbTask()
    {
        $connection = new Connection(array(
            "host" => "localhost",
            "username" => "root",
            "password" => "secret",
            "dbname" => "invo"
        ));

        // ...
    }

}

$some = new SomeComponent();
$some->someDbTask();

为了解决上面所说的问题,我们需要在使用前创建一个外部连接,并注入到容器中。就目前而言,这看起来是一个很好的解决方案:

<?php

class SomeComponent
{

    protected $_connection;

    /**
     * Sets the connection externally
     */
    public function setConnection($connection)
    {
        $this->_connection = $connection;
    }

    public function someDbTask()
    {
        $connection = $this->_connection;

        // ...
    }

}

$some = new SomeComponent();

//Create the connection
$connection = new Connection(array(
    "host" => "localhost",
    "username" => "root",
    "password" => "secret",
    "dbname" => "invo"
));

//Inject the connection in the component
$some->setConnection($connection);

$some->someDbTask();

现在我们来考虑一个问题,我们在应用程序中的不同地方使用此组件,将多次创建数据库连接。使用一种类似全局注册表的方式,从这获得一个数据库连接实例,而不是使用一次就创建一次。

<?php

class Registry
{

    /**
     * Returns the connection
     */
    public static function getConnection()
    {
       return new Connection(array(
            "host" => "localhost",
            "username" => "root",
            "password" => "secret",
            "dbname" => "invo"
        ));
    }

}

class SomeComponent
{

    protected $_connection;

    /**
     * Sets the connection externally
     */
    public function setConnection($connection){
        $this->_connection = $connection;
    }

    public function someDbTask()
    {
        $connection = $this->_connection;

        // ...
    }

}

$some = new SomeComponent();

//Pass the connection defined in the registry
$some->setConnection(Registry::getConnection());

$some->someDbTask();

现在,让我们来想像一下,我们必须在组件中实现两个方法,首先需要创建一个新的数据库连接,第二个总是获得一个共享连接:

<?php

class Registry
{

    protected static $_connection;

    /**
     * Creates a connection
     */
    protected static function _createConnection()
    {
        return new Connection(array(
            "host" => "localhost",
            "username" => "root",
            "password" => "secret",
            "dbname" => "invo"
        ));
    }

    /**
     * Creates a connection only once and returns it
     */
    public static function getSharedConnection()
    {
        if (self::$_connection===null){
            $connection = self::_createConnection();
            self::$_connection = $connection;
        }
        return self::$_connection;
    }

    /**
     * Always returns a new connection
     */
    public static function getNewConnection()
    {
        return self::_createConnection();
    }

}

class SomeComponent
{

    protected $_connection;

    /**
     * Sets the connection externally
     */
    public function setConnection($connection){
        $this->_connection = $connection;
    }

    /**
     * This method always needs the shared connection
     */
    public function someDbTask()
    {
        $connection = $this->_connection;

        // ...
    }

    /**
     * This method always needs a new connection
     */
    public function someOtherDbTask($connection)
    {

    }

}

$some = new SomeComponent();

//This injects the shared connection
$some->setConnection(Registry::getSharedConnection());

$some->someDbTask();

//Here, we always pass a new connection as parameter
$some->someOtherDbTask(Registry::getConnection());

到此为止,我们已经看到了如何使用依赖注入解决我们的问题。不是在代码内部创建依赖关系,而是让其作为一个参数传递,这使得我们的程序更容易维护,降低程序代码的耦合度,实现一种松耦合。但是从长远来看,这种形式的依赖注入也有一些缺点。

例如,如果组件中有较多的依赖关系,我们需要创建多个setter方法传递,或创建构造函数进行传递。另外,每次使用组件时,都需要创建依赖组件,使代码维护不太易,我们编写的代码可能像这样:

<?php

//Create the dependencies or retrieve them from the registry
$connection = new Connection();
$session = new Session();
$fileSystem = new FileSystem();
$filter = new Filter();
$selector = new Selector();

//Pass them as constructor parameters
$some = new SomeComponent($connection, $session, $fileSystem, $filter, $selector);

// ... or using setters

$some->setConnection($connection);
$some->setSession($session);
$some->setFileSystem($fileSystem);
$some->setFilter($filter);
$some->setSelector($selector);

我想,我们不得不在应用程序的许多地方创建这个对象。如果你不需要依赖的组件后,我们又要去代码注入部分移除构造函数中的参数或者是setter方法。为了解决这个问题,我们再次返回去使用一个全局注册表来创建组件。但是,在创建对象之前,它增加了一个新的抽象层:

<?php

class SomeComponent
{

    // ...

    /**
     * Define a factory method to create SomeComponent instances injecting its dependencies
     */
    public static function factory()
    {

        $connection = new Connection();
        $session = new Session();
        $fileSystem = new FileSystem();
        $filter = new Filter();
        $selector = new Selector();

        return new self($connection, $session, $fileSystem, $filter, $selector);
    }

}

这一刻,我们好像回到了问题的开始,我们正在创建组件内部的依赖,我们每次都在修改以及找寻一种解决问题的办法,但这都不是很好的做法。

一种实用和优雅的来解决这些问题,是使用容器的依赖注入,像我们在前面看到的,容器作为全局注册表,使用容器的依赖注入做为一种桥梁来解决依赖可以使我们的代码耦合度更低,很好的降低了组件的复杂性:

<?php

class SomeComponent
{

    protected $_di;

    public function __construct($di)
    {
        $this->_di = $di;
    }

    public function someDbTask()
    {

        // Get the connection service
        // Always returns a new connection
        $connection = $this->_di->get('db');

    }

    public function someOtherDbTask()
    {

        // Get a shared connection service,
        // this will return the same connection everytime
        $connection = $this->_di->getShared('db');

        //This method also requires a input filtering service
        $filter = $this->_db->get('filter');

    }

}

$di = new Phalcon\DI();

//Register a "db" service in the container
$di->set('db', function(){
    return new Connection(array(
        "host" => "localhost",
        "username" => "root",
        "password" => "secret",
        "dbname" => "invo"
    ));
});

//Register a "filter" service in the container
$di->set('filter', function(){
    return new Filter();
});

//Register a "session" service in the container
$di->set('session', function(){
    return new Session();
});

//Pass the service container as unique parameter
$some = new SomeComponent($di);

$some->someTask();

现在,该组件只有访问某种service的时候才需要它,如果它不需要,它甚至不初始化,以节约资源。该组件是高度解耦。他们的行为,或者说他们的任何其他方面都不会影响到组件本身。

我们的实现办法

Phalcon\DI 是一个实现了服务的依赖注入功能的组件,它本身也是一个容器。

由于Phalcon高度解耦,Phalcon\DI 是框架用来集成其他组件的必不可少的部分,开发人员也可以使用这个组件依赖注入和管理应用程序中不同类文件的实例。

基本上,这个组件实现了 Inversion of Control 模式。基于此,对象不再以构造函数接收参数或者使用setter的方式来实现注入,而是直接请求服务的依赖注入。这就大大降低了整体程序的复杂性,因为只有一个方法用以获得所需要的一个组件的依赖关系。

此外,这种模式增强了代码的可测试性,从而使它不容易出错。

在容器中注册服务

框架本身或开发人员都可以注册服务。当一个组件A要求调用组件B(或它的类的一个实例),可以从容器中请求调用组件B,而不是创建组件B的一个实例。

这种工作方式为我们提供了许多优点:

  • 我们可以更换一个组件,从他们本身或者第三方轻松创建。
  • 在组件发布之前,我们可以充分的控制对象的初始化,并对对象进行各种设置。
  • 我们可以使用统一的方式从组件得到一个结构化的全局实例

服务可以通过以下几种方式注入到容器:

<?php

//Create the Dependency Injector Container
$di = new Phalcon\DI();

//By its class name
$di->set("request", 'Phalcon\Http\Request');

//Using an anonymous function, the instance will lazy loaded
$di->set("request", function(){
    return new Phalcon\Http\Request();
});

//Registering directly an instance
$di->set("request", new Phalcon\Http\Request());

//Using an array definition
$di->set("request", array(
    "className" => 'Phalcon\Http\Request'
));

在上面的例子中,当向框架请求访问一个请求数据时,它将首先确定容器中是否存在这个”reqeust”名称的服务。

容器会反回一个请求数据的实例,开发人员最终得到他们想要的组件。

在上面示例中的每一种方法都有优缺点,具体使用哪一种,由开发过程中的特定场景来决定的。

用一个字符串来设定一个服务非常简单,但缺少灵活性。设置服务时,使用数组则提供了更多的灵活性,而且可以使用较复杂的代码。lambda函数是两者之间一个很好的平衡,但也可能导致更多的维护管理成本。

Phalcon\DI 提供服务的延迟加载。除非开发人员在注入服务的时候直接实例化一个对象,然后存存储到容器中。在容器中,通过数组,字符串等方式存储的服务都将被延迟加载,即只有在请求对象的时候才被初始化。

<?php

//Register a service "db" with a class name and its parameters
$di->set("db", array(
    "className" => "Phalcon\Db\Adapter\Pdo\Mysql",
    "parameters" => array(
          "parameter" => array(
               "host" => "localhost",
               "username" => "root",
               "password" => "secret",
               "dbname" => "blog"
          )
    )
));

//Using an anonymous function
$di->set("db", function(){
    return new Phalcon\Db\Adapter\Pdo\Mysql(array(
         "host" => "localhost",
         "username" => "root",
         "password" => "secret",
         "dbname" => "blog"
    ));
});

以上这两种服务的注册方式产生相同的结果。然后,通过数组定义的,在后面需要的时候,你可以修改服务参数:

<?php

$di->setParameter("db", 0, array(
    "host" => "localhost",
    "username" => "root",
    "password" => "secret"
));

从容器中获得服务的最简单方式就是使用”get”方法,它将从容器中返回一个新的实例:

<?php $request = $di->get("request");

或者通过下面这种魔术方法的形式调用:

<?php

$request = $di->getRequest();

Phalcon\DI 同时允许服务重用,为了得到一个已经实例化过的服务,可以使用 getShared() 方法的形式来获得服务。

具体的 Phalcon\Http\Request 请求示例:

<?php

$request = $di->getShared("request");

参数还可以在请求的时候通过将一个数组参数传递给构造函数的方式:

<?php

$component = $di->get("MyComponent", array("some-parameter", "other"))

Factory Default DI

虽然Phalcon在解耦方面为我们提供了很大的自由度和灵活性,也许我们只是单纯的把它当作一个full-stack的框架来使用。为了实现这一目标,该框架提供了 Phalcon\DI 的一个变种 Phalcon\DI\FactoryDefault 。这个类会自动注册相应的服务,使各种服务组件绑定到框架。

<?php $di = new Phalcon\DI\FactoryDefault();

服务命名约定

虽然你可以任意注入你想要的服务(名称)到容器中,但Phalcon有一系列的命名约定,使用它们以能得到适当的服务。

Service Name Description Default Shared
dispatcher Controllers Dispatching Service Phalcon\Mvc\Dispatcher Yes
router Routing Service Phalcon\Mvc\Router Yes
url URL Generator Service Phalcon\Mvc\Url Yes
request HTTP Request Environment Service Phalcon\Http\Request Yes
response HTTP Response Environment Service Phalcon\Http\Response Yes
filter Input Filtering Service Phalcon\Filter Yes
flash Flash Messaging Service Phalcon\Flash\Direct Yes
session Session Service Phalcon\Session\Adapter\Files Yes
eventsManager Events Management Service Phalcon\Events\Manager Yes
db Low-Level Database Connection Service Phalcon\Db Yes
modelsManager Models Management Service Phalcon\Mvc\Model\Manager Yes
modelsMetadata Models Meta-Data Service Phalcon\Mvc\Model\MetaData\Memory Yes
transactionManager Models Transaction Manager Service Phalcon\Mvc\Model\Transaction\Manager Yes
modelsCache Cache backend for models cache None
viewsCache Cache backend for views fragments None

Instantiating classes via the Services Container

当你向服务容器请求服务的时候,如果在容器中找不到这个服务,它会尝试加载具有相同名称的一个类,通过这种行为,我们可以使用注册为一个服务的形式来获取一个类的实例:

<?php

//Register a controller as a service
$di->set('IndexController', function() {
    $component = new Component();
    return $component;
});

//Register a controller as a service
$di->set('MyOtherComponent', function() {
    //Actually returns another component
    $component = new AnotherComponent();
    return $component;
});

//Create a instance via the services container
$myComponent = $di->get('MyOtherComponent');

你可以利用这个特点,总是通过向服务容器(即使它们没有被注册为服务)请求服务来获得类的实例,DI会通过 autoloader 加载的类返回一个类的实例。

Accessing the DI in a static way

如果你需要,你还可以通过以下的方式使用DI来创建一个静态函数

<?php

class SomeComponent
{

    public static function someMethod()
    {
        $session = Phalcon\DI::getDefault()->getShared('session');
    }

}

MVC架构

Phalcon提供了面向对象的类,用以在应用程序中实现模型,视图,控制器架构(通常我们称之为 MVC 架构)。这种设计模式被广泛的应用到其他Web框架以及桌面应用程序中。

MVC的好处包括:

  • 分离业务逻辑与用户界面以及数据库层
  • 清晰的代码结构,使代码更容易维护

如果你决定使用MVC架构来开发你的程序,那么应用程序的每个请求都将采用 MVC 架构的方式来管理。Phalcon是一个采用C语言开发的php框架,这种模式是一种可以很好的提供高性能的方法。

模型

A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models. Learn more

视图

Views represent the user interface of your application. Views are often HTML files with embedded PHP code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application. Learn more

控制器

The controllers provide the “flow” between models and views. Controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation. Learn more

控制器

控制器提供了一些方法,他们被叫做actions。Actions是控制器用来处理用户请求的方法。默认情况下,控制器的所有公有的方法都映射到一个可访问的URL。Actions是负责解释请求以及创建用户响应的。通过的反应是一个渲染视图的形式,但也有其他的形式来处理用户请求。

例如,当你访问一个这样的URL时 http://localhost/blog/posts/show/2012/the-post-title ,默认情况下,Phalcon是这样对URL进行分解的:

Phalcon Directory blog
Controller posts
Action show
Parameter 2012
Parameter the-post-title

在这个例子中,PostController控制器用于来接收用户请求。由于在应用程序中没有对controllers的存放指定存放位置,他们可以通过 autoloaders 来自动加载你的controllers目录。

所有的控制器都必须以“Controller”为结尾,所有的Actions都是以“Action”结尾。下面是一个控制器的示例:

译者注:也并非所有的控制器都必须以“Controller”为结尾的,比如我们一般会写一个名为 “ContollerBase”,让他继承自 PhalconMvcController. 同时我们自己应用程序中的其他控制器都再继承自 ContollerBase.这么来做的话,则控制器ContollerBase就不是以 “Controller”为结尾了。如果严谨一点来讲可以这么说,所以用于用户请求的控制器必须以“Controller”为结尾

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function showAction($year, $postTitle)
    {

    }

}

其他的URI参数将被定义为Action参数,因此你可以很容易的使用局部变量来访问这些参数。控制器继承自 Phalcon\Mvc\Controller 。 这样一来,你的控制器就很方便的提供应用服务了

Dispatch Loop

其他的URI参数将被定义为Action参数,因此你可以很容易的使用局部变量来访问这些参数。控制器继承自 Phalcon\Mvc\Controller 。 这样一来,你的控制器就很方便的访问应用程序中的其他服务了

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function showAction($year, $postTitle)
    {
        $this->flash->error("You don't have permission to access this area");

        // Forward flow to another action
        $this->dispatcher->forward(array(
            "controller" => "users",
            "action" => "signin"
        ));
    }

}

如果用户没有权限访问某个特定的动作,然后将被转发到UsersController控制器的signinAction

<?php

class UsersController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function signinAction()
    {

    }

}

应用程序中并没有限制分发器的跳转次数,只要他们不导致死循环,可以正常停止即可。如果程序逻辑中再没有跳转到其他的Action,程序将自动调用MVC的视图层 Phalcon\Mvc\View.

初始化控制器

Phalcon\Mvc\Controller 提供初始化的方法,它最先执行,注意:”__construct” 的初始化方法在这里不推荐使用。

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public $settings;

    public function initialize()
    {
        $this->settings = array(
            "mySetting" => "value"
        );
    }

    public function saveAction()
    {
        if ($this->settings["mySetting"] == "value") {
            //...
        }
    }

}

访问注入服务

如果控制器继承自 Phalcon\Mvc\Controller ,那么它将可以很方便的访问应用程序容器中的其他服务。例如,我们注册了一个这样的服务:

<?php

$di = new Phalcon\DI();

$di->set('storage', function(){
    return new Storage('/some/directory');
}, true);

然后,我们可以通过以下方式访问那些服务:

<?php

class FilesController extends \Phalcon\Mvc\Controller
{

    public function saveAction()
    {

        //Injecting the service by just accessing the property with the same name
        $this->storage->save('/some/file');

        //Accessing the service from the DI
        $this->di->get('storage')->save('/some/file');

        //Another way to access the service using the magic getter
        $this->di->getStorage()->save('/some/file');

        //Another way to access the service using the magic getter
        $this->getDi()->getStorage()->save('/some/file');
    }

}

如果你正在使用Phalcon框架,你可以阅读一下DI by default

请求和响应

假设,该框架已经提供了一组预置的服务。我们将解释他们如何与http相互协调工作。”request”服务是 Phalcon\Http\Request 的一个实例对象, “response”是 Phalcon\Http\Response 的一个实例对象,它负责向客户端发送响应内容。

<?php

class PostsController extends Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function saveAction()
    {

        // Check if request has made with POST
        if ($this->request->isPost() == true) {
            // Access POST data
            $customerName = $this->request->getPost("name");
            $customerBorn = $this->request->getPost("born");
        }
    }

}

The response object is not usually used directly, but is built up before the execution of the action, sometimes - like in an afterDispatch event - it can be useful to access the response directly:

<?php

class PostsController extends Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function notFoundAction()
    {
        // Send a HTTP 404 response header
        $this->response->setStatusCode(404, "Not Found");
    }

}

学习更多的关于HTTP环境相关的文章,请查阅 request 以及 response.

Session 数据

Sessions help us maintain persistent data between requests. You could access a Phalcon\Session\Bag from any controller to encapsulate data that need to be persistent.

<?php

class UserController extends Phalcon\Mvc\Controller
{

    public function indexAction()
    {
        $this->persistent->name = "Michael";
    }

    public function welcomeAction()
    {
        echo "Welcome, ", $this->persistent->name;
    }

}

注入服务替代控制器

控制器可以注册成为服务,这样的话,用户的请求都会从注册的控制器获得。因此,用此种办法可以很容易的取代其他控制器。

<?php

//Register a controller as a service
$di->set('IndexController', function() {
    $component = new Component();
    return $component;
});

译者注:

以上例来说明,如果要访问 /index/index 的话,则需要在类 Component 中编写 indexAction() 方法。即和控制器中的action写法是相同的。同时,即使控制器目录存在 IndexController,也将不再访问。而是直接输出 Component中indexAction()的内容

创建一个基础控制器类

在应用程序的控制器中经常会需要访问控制列表,多语言,缓存,模板引擎等。在这种情况下,我们一般建议你创建一个 “base controller”,以防重复造轮子,保持代码 DRY .控制器只是一个简单的类文件,他要继承自 Phalcon\Mvc\Controller ,其他的控制器再继承自 “base controller”,这样就可以拥有基类控制器中的通用功能了,你的代码就会更整洁一些。

这个类可以放到任何目录下,但按照一般的规则来讲,我们推荐你把它放到控制器文件夹中,比如 apps/controllers/ControllerBase.php 。我们可能会需要这个文件,你可以直接在程序中引入,或者通过Phalcon的autoloader引入:

<?php

require "../app/controllers/ControllerBase.php";

一般通用的功能组件,我们可以写到这个文件中,比如 (actions,methods, properties等):

<?php

class ControllerBase extends \Phalcon\Mvc\Controller
{

  /**
   * This action is available for multiple controllers
   */
  public function someAction()
  {

  }

}

其他继承自ControllerBase的控制器,会自动获得通用组件。

译者注: 只要明白类继承是怎么回事,这块就非常好理解了。

<?php

class UsersController extends ControllerBase
{

}

译者补充:

我在这里多加一个例子,你就可以很容易的明白 base controller的用处了。

比如,我们一般会在控制器中做跳转操作,一般会用到 dispatcher的 forward方法。但这个forward方法的参数是一个数组,需要这样写:

<?php
class UsersController extends ControllerBase
{
    public function authAction()
    {
        ..... //valiate code
        $this->dispatcher->forward(array(
              'controller' => 'users',
              'action' => 'login'
           )
        );
    }
}

以上面示例中的写法来说,会有些麻烦。那么我们需要在 base controller中加入一个自定义的 forward 方法。

<?php
class ControllerBase extends \Phalcon\Mvc\Controller
{
   protected function forward($uri){
     $uriParts = explode('/', $uri);
     return $this->dispatcher->forward(
        array(
           'controller' => $uriParts[0],
           'action' => $uriParts[1]
        )
     );
   }
}

再次来修改 UsersController中的authAction方法:

<?php
class UsersController extends ControllerBase
{
    public function authAction()
    {
        ..... //valiate code

        $this->forward('users/login');
    }
}

是不是非常方便了?

控制器中的事件

控制器本身也可以充当监听的身份,通过 dispatcher 事件,在控制器中实现 dispatcher的事件方法,控制器的方法名要与事件名相同。这样的话,你就可以很方便的在actions执行前后通过钩点执行其他内容:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function beforeExecuteRoute($dispatcher)
    {
        // This is executed before every found action

        if ($dispatcher->getActionName() == 'save') {
            $this->flash->error("You don't have permission to save posts");
            return false;
        }
    }

    public function afterExecuteRoute($dispatcher)
    {
        // Executed after every found action
    }

}

使用模型(Working with Models)

在应用程序中,模型是代表的是一种数据以及通过一些规则来操作这些数据,模型主要用于通过一些规则使其与数据库表进行相互操作,在大多数情况下,每个数据库表将对应到一个模型,整个应用程序的业务逻辑都会集中在模型中。

Phalcon\Mvc\Model 是应用程序中所有模型的基类,它保证了数据库的独立性,基本的CURD操作,高级的查询功能,多表关联等功能。

Phalcon\Mvc\Model 提供了SQL语句的动态转化功能,避免了直接使用SQL语句带来的安全风险。

Models是数据库的高级抽象层,如果您需要与数据库直接打交道,你可以查看 Phalcon\Db 组件文档。

创建模型

一个Model就是一个继承自 Phalcon\Mvc\Model 的类文件,它必须放到models文件夹目录下,一个Model文件必须是一个独立的类文件,同时它的命名采用驼蜂式的书写方法:

<?php

class Robots extends \Phalcon\Mvc\Model
{

}

上面的例子是一个 “Robots”模型类,需要注意的是,类Robots继承自 Phalcon\Mvc\Model。因为继承,该模型提供了大量的功能,包括基本的数据库CRUDCreate, Read, Update, Destroy) 操作,数据验证,先进的检索功能,并且可以同时关联多个模型。

推荐你使用PHP5.4版本,这可以使得模型中的属性在保存到内存时,更节省内存。

默认情况下,模型”Robots”对应的是数据库表”robots”,如果你想手工指定映射到其他的数据库表,你可以使用 getSource() 方法:

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function getSource()
    {
        return "the_robots";
    }

}

此时,模型”Robots”映射到数据库表”the_robots”,initialize()方法有助于在模型中建立自定义行为,如,不同的数据表。initialize()方法在请求期间只被调用一次。

在模型中使用命名空间

命名空间可以用来避免类名冲突,在这种情况下,使用getSource()方法来指定数据表名称是必要的:

<?php

namespace Store\Toys;

class Robots extends \Phalcon\Mvc\Model
{

    public function getSource()
    {
        return "robots";
    }

}

Understanding Records To Objects

每一个模型对象表示数据表中的一行数据,你可以轻松的通过读取对象的属性来访问数据。举个例子,数据表”robots”的记录如下:

mysql> select * from robots;
+----+------------+------------+------+
| id | name       | type       | year |
+----+------------+------------+------+
|  1 | Robotina   | mechanical | 1972 |
|  2 | Astro Boy  | mechanical | 1952 |
|  3 | Terminator | cyborg     | 2029 |
+----+------------+------------+------+
3 rows in set (0.00 sec)

你可以通过数据库主键查找某条记录,然后打印出它们的名字:

<?php

// Find record with id = 3
$robot = Robots::findFirst(3);

// Prints "Terminator"
echo $robot->name;

一旦记录被读取到内存中,你可以修改它的数据,然后保存更改:

<?php

$robot = Robots::findFirst(3);
$robot->name = "RoboCop";
$robot->save();

正如你所看到的,这里没有使用原始的SQL语句。Phalcon\Mvc\Model 为web应用程序提供了高度的数据库抽象。

查找记录

Phalcon\Mvc\Model 还提供了多种方法来查询数据记录。下面的例子将为你展示如何通过Model查询单条以及多条记录:

<?php

// How many robots are there?
$robots = Robots::find();
echo "There are ", count($robots), "\n";

// How many mechanical robots are there?
$robots = Robots::find("type = 'mechanical'");
echo "There are ", count($robots), "\n";

// Get and print virtual robots ordered by name
$robots = Robots::find(array(
    "type = 'virtual'",
    "order" => "name"
));
foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// Get first 100 virtual robots ordered by name
$robots = Robots::find(array(
    "type = 'virtual'",
    "order" => "name",
    "limit" => 100
));
foreach ($robots as $robot) {
   echo $robot->name, "\n";
}

你也可以使用findFirst()方法来获取给定条件下的第一条记录:

<?php

// What's the first robot in robots table?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name, "\n";

// What's the first mechanical robot in robots table?
$robot = Robots::findFirst("type = 'mechanical'");
echo "The first mechanical robot name is ", $robot->name, "\n";

// Get first virtual robot ordered by name
$robot = Robots::findFirst(array("type = 'virtual'", "order" => "name"));
echo "The first virtual robot name is ", $robot->name, "\n";

find()和findFirst()这两个方法都接收一个关联数组作为检索条件:

<?php

$robot = Robots::findFirst(
    array(
        "type = 'virtual'",
        "order" => "name DESC",
        "limit" => 30
    )
);

$robots = Robots::find(
    array(
        "conditions" => "type = ?1",
        "bind"       => array(1 => "virtual")
    )
);

可用的查询选项列表:

Parameter Description Example
conditions Search conditions for the find operation. Is used to extract only those records that fulfill a specified criterion. By default PhalconMvcModel assumes the first parameter are the conditions. “conditions” => “name LIKE ‘steve%’”
bind Bind is used together with options, by replacing placeholders and escaping values thus increasing security “bind” => array(“status” => “A”, “type” => “some-time”)
bindTypes When binding parameters, you can use this parameter to define additional casting to the bound parameters increasing even more the security “bindTypes” => array(Column::BIND_TYPE_STR, Column::BIND_TYPE_INT)
order Is used to sort the resultset. Use one or more fields separated by commas. “order” => “name DESC, status”
limit Limit the results of the query to results to certain range “limit” => 10
group Allows to collect data across multiple records and group the results by one or more columns “group” => “name, status”
for_update With this option, Phalcon\Mvc\Model reads the latest available data, setting exclusive locks on each row it reads “for_update” => true
shared_lock With this option, Phalcon\Mvc\Model reads the latest available data, setting shared locks on each row it reads “shared_lock” => true
cache Cache the resulset, reducing the continuous access to the relational system “cache” => array(“lifetime” => 3600, “key” => “my-find-key”)

如果你愿意,你也可以通过面向对象的方式创建查询,而不是使用上面讲到的关联数组的形式:

<?php

$robots = Robots::query()
    ->where("type = :type:")
    ->bind(array("type" => "mechanical"))
    ->order("name")
    ->execute();

静态方法 query()返回一个 Phalcon\Mvc\Model\Criteria 的实例化对象,因此它对IDE自动提示功能非常友好。

所有的查询都被进行内部处理成 PHQL 。PHQL是一个高层次的,面向对象的类SQL语言。这种语言为你提供更多的功能来进行查询,如与其他模型关联查询,定义分组,添加聚合等。

模型数据集(Model Resultsets)

findFirst()方法直接返回一个类的实例对象(查询有数据返回的时候),find()方法则返回:doc:Phalcon\Mvc\Model\Resultset\Simple <../api/Phalcon_Mvc_Model_Resultset_Simple> 的一个实例对象,这个对象是一个封装了所有功能的结果集,比如像数据遍历,寻找特定的数据记录,计数等等。

这些对象比标准数组更为强大,最大的优点之一是 Phalcon\Mvc\Model\Resultset 在任何时候它在内存中只保存一条记录,这极大的优化了内存管理,特别是处理大量数据的时候。

<?php

// Get all robots
$robots = Robots::find();

// Traversing with a foreach
foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// Traversing with a while
$robots->rewind();
while ($robots->valid()) {
    $robot = $robots->current();
    echo $robot->name, "\n";
    $robots->next();
}

// Count the resultset
echo count($robots);

// Alternative way to count the resultset
echo $robots->count();

// Move the internal cursor to the third robot
$robots->seek(2);
$robot = $robots->current()

// Access a robot by its position in the resultset
$robot = $robots[5];

// Check if there is a record in certain position
if (isset($robots[3]) {
   $robot = $robots[3];
}

// Get the first record in the resultset
$robot = robots->getFirst();

// Get the last record
$robot = robots->getLast();

Phalcon数据集模拟游标的方式,你可以获取任意一行数据,只需要通过访问其位置,或者通过移动内部指针到一个特定的位置。需要注意的是,一些数据库系统并不支持游标,这将会导致每次强制重新执行,游标移动到头部,并从头到尾去查询请求位置。同理,如果一个结果集遍历多次,查询必须被执行相同的次数。

大量的查询结果存储在内存中,会消耗大量的资源。resultsets are obtained from the database in chunks of 32 rows reducing the need for re-execute the request in several cases.

请注意,结果集可以被序列化后存储到缓存中。Phalcon\Cache 可以帮助完成这项任务。However, serializing data causes Phalcon\Mvc\Model to retrieve all the data from the database in an array, thus consuming more memory while this process takes place.

<?php

// Query all records from model parts
$parts = Parts::find();

// Store the resultset into a file
file_put_contents("cache.txt", serialize($parts));

// Get parts from file
$parts = unserialize(file_get_contents("cache.txt"));

// Traverse the parts
foreach ($parts as $part) {
   echo $part->id;
}
参数绑定

Phalcon\Mvc\Model 同样支持参数类型绑定。虽然会有比较小的性能消耗,但我们推荐你使用这种方法,因为它会清除SQL注入攻击,字符串过滤及整形数据验证等。绑定绑定,可以通过如下方式实现:

<?php

// Query robots binding parameters with string placeholders
$conditions = "name = :name: AND type = :type:";

//Parameters whose keys are the same as placeholders
$parameters = array(
    "name" => "Robotina",
    "type" => "maid"
);

//Perform the query
$robots = Robots::find(array(
    $conditions,
    "bind" => $parameters
));

// Query robots binding parameters with integer placeholders
$conditions = "name = ?1 AND type = ?2";
$parameters = array(1 => "Robotina", 2 => "maid");
$robots     = Robots::find(array(
    $conditions,
    "bind" => $parameters
));

// Query robots binding parameters with both string and integer placeholders
$conditions = "name = :name: AND type = ?1";

//Parameters whose keys are the same as placeholders
$parameters = array(
    "name" => "Robotina",
    1 => "maid"
);

//Perform the query
$robots = Robots::find(array(
    $conditions,
    "bind" => $parameters
));

当使用数字时,你可能需要定义他们为整形数字。比如 1或2, 在这种情况下,有可能是字符串”1”或”2”,而不是数字,所以这是不正确的。

在使用 PDO 的时候字符串是被自动转义的,此功能和数据库连接的字符集有关,所以在进行数据库连接时,必须设置正确的连接参数或者在数据库中设置好,错误的字符集会导致数据在存储读取时产生意想不到的结果。

此外,你还可以通过设置参数”bindTypes”,定义参数的数据类型:

<?php

//Bind parameters
$parameters = array(
    "name" => "Robotina",
    "year" => 2008
);

//Casting Types
$types = array(
    Phalcon\Db\Column::BIND_PARAM_STR,
    Phalcon\Db\Column::BIND_PARAM_INT
);

// Query robots binding parameters with string placeholders
$conditions = "name = :name: AND year = :year:";
$robots = Robots::find(array(
    $conditions,
    "bind" => $parameters,
    "bindTypes" => $types
));

参数绑定可以用于所有的查询方法上,比如find()和findFirst()。当然也包括一些计算类的方法,如 count(),sum(),average()等。

模型之间的关系

共有四种类型的关系:一对一,一对多,多对一,多对多。关系可以是单向也可以是双向的,并且每个可以是简单的(一个一个的Model)或者更复杂的(组合Model)。模型管理器管理这些关系的外键约束,这将有助于定义参照完整性以及方便快捷的访问关联数据。通过关系映射,可以在一个记录中很容易的访问相关模型中的数据。

单向关系

Unidirectional relations are those that are generated in relation to one another but not vice versa.

双向关系

The bidirectional relations build relationships in both models and each model defines the inverse relationship of the other.

定义关系

在Phalcon中,关系的定义必须在model的initialize()方法中进行定义,通过方法belongsTo(),hasOne(), hasMany() 进行关联关系,用当前模型的属性关联其他模型。这几个方法都需要3个参数,即: 当前模型属性,关联模型名称,关联模型的属性。

Method Description
hasMany Defines a 1-n relationship
hasOne Defines a 1-1 relationship
belongsTo Defines a n-1 relationship

下面的schema显示了三个数据表的关系,用这个作为例子有助于我们更好的理解:

CREATE TABLE `robots` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `name` varchar(70) NOT NULL,
    `type` varchar(32) NOT NULL,
    `year` int(11) NOT NULL,
    PRIMARY KEY (`id`)
);

CREATE TABLE `robots_parts` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `robots_id` int(10) NOT NULL,
    `parts_id` int(10) NOT NULL,
    `created_at` DATE NOT NULL,
    PRIMARY KEY (`id`),
    KEY `robots_id` (`robots_id`),
    KEY `parts_id` (`parts_id`)
);

CREATE TABLE `parts` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `name` varchar(70) NOT NULL,
    PRIMARY KEY (`id`)
);
  • The model “Robots” has many “RobotsParts”.
  • The model “Parts” has many “RobotsParts”.
  • The model “RobotsParts” belongs to both “Robots” and “Parts” models as a one-to-many relation.

在模型中他们的实现方法是这样的:

<?php

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasMany("id", "RobotsParts", "robots_id");
    }

}
<?php

class Parts extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->hasMany("id", "RobotsParts", "parts_id");
    }

}
<?php

class RobotsParts extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->belongsTo("robots_id", "Robots", "id");
        $this->belongsTo("parts_id", "Parts", "id");
    }

}

在映射关系中,第一个参数是当前模型的属性,第二个参数为关联模型的类名称,第三个参数为关联模型的属性。你也可以在映射关系中使用数组定义多个属性。

Taking advantage of relationships

当明确定义了模型之间的关系后,就很容易通过查找到的记录找到相关模型的记录

<?php

$robot = Robots::findFirst(2);
foreach ($robot->getRobotsParts() as $robotPart) {
    echo $robotPart->getParts()->name, "\n";
}

Phalcon使用魔术方法 __call来获得关联模型的数据。如果被调用的方法中含有”get”前辍,Phalcon\Mvc\Model 将返回 findFirst()/find()的结果集。下面的示例展示了使用和未使用魔术方法获取数据的区别:

<?php

$robot = Robots::findFirst(2);

// Robots model has a 1-n (hasMany)
// relationship to RobotsParts then
$robotsParts = $robot->getRobotsParts();

// Only parts that match conditions
$robotsParts = $robot->getRobotsParts("created_at = '2012-03-15'");

// Or using bound parameters
$robotsParts = $robot->getRobotsParts(array(
    "created_at = :date:",
    "bind" => array("date" => "2012-03-15"
)));

$robotPart = RobotsParts::findFirst(1);

// RobotsParts model has a n-1 (belongsTo)
// relationship to RobotsParts then
$robot = $robotPart->getRobots();

Getting related records manually:

<?php

$robot = Robots::findFirst(2);

// Robots model has a 1-n (hasMany)
// relationship to RobotsParts then
$robotsParts = RobotsParts::find("robots_id = '" . $robot->id . "'");

// Only parts that match conditions
$robotsParts = RobotsParts::find(
    "robots_id = '" . $robot->id . "' AND created_at='2012-03-15'"
);

$robotPart = RobotsParts::findFirst(1);

// RobotsParts model has a n-1 (belongsTo)
// relationship to RobotsParts then
$robot = Robots::findFirst("id = '" . $robotPart->robots_id . "'");

前辍”get”使用find()/findFirst()来获取关联记录。当然你也可以”count”前辍来获取记录的数量:

<?php

$robot = Robots::findFirst(2);
echo "The robot have ", $robot->countRobotsParts(), " parts\n";
虚拟外键

默认情况下,关联关系并不定义外键约束,也就是说,如果你尝试insert/update数据的话,将不会进行外键验证,Phalcon也不会提示验证信息。你可以修改此行为,增加一个参数定义这种关系。

RobotsPart模型可以这样修改,以实现此功能:

<?php

class RobotsParts extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->belongsTo("robots_id", "Robots", "id", array(
            "foreignKey" => true
        ));

        $this->belongsTo("parts_id", "Parts", "id", array(
            "foreignKey" => array(
                "message" => "The part_id does not exist on the parts model"
            )
        ));
    }

}

如果你在belongsTo()中设置了外键约束,它将会验证insert/update的值是不是一个有效的值。同样地,如果你在hasMany()/hasOne()中设置了外键约束,它将会验证记录是否可以删除。

<?php

class Parts extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->hasMany("id", "RobotsParts", "parts_id", array(
            "foreignKey" => array(
                "message" => "The part cannot be deleted because other robots are using it"
            )
        ));
    }

}

Generating Calculations

数量统计是数据库中常用的功能,如COUNT,SUM,MAX,MIN,AVG. Phalcon\Mvc\Model 可以通过公开的方法实现此种功能。

Count examples:

<?php

// How many employees are?
$rowcount = Employees::count();

// How many different areas are assigned to employees?
$rowcount = Employees::count(array("distinct" => "area"));

// How many employees are in the Testing area?
$rowcount = Employees::count("area = 'Testing'");

//Count employees grouping results by their area
$group = Employees::count(array("group" => "area"));
foreach ($group as $row) {
   echo "There are ", $group->rowcount, " in ", $group->area;
}

// Count employees grouping by their area and ordering the result by count
$group = Employees::count(
    array(
        "group" => "area",
        "order" => "rowcount"
    )
);

Sum examples:

<?php

// How much are the salaries of all employees?
$total = Employees::sum(array("column" => "salary"));

// How much are the salaries of all employees in the Sales area?
$total = Employees::sum(
    array(
        "column"     => "salary",
        "conditions" => "area = 'Sales'"
    )
);

// Generate a grouping of the salaries of each area
$group = Employees::sum(
    array(
        "column" => "salary",
        "group"  => "area"
    )
);
foreach ($group as $row) {
   echo "The sum of salaries of the ", $group->area, " is ", $group->sumatory;
}

// Generate a grouping of the salaries of each area ordering
// salaries from higher to lower
$group = Employees::sum(
    array(
        "column" => "salary",
        "group"  => "area",
        "order"  => "sumatory DESC"
    )
);

Average examples:

<?php

// What is the average salary for all employees?
$average = Employees::average(array("column" => "salary"));

// What is the average salary for the Sales's area employees?
$average = Employees::average(
    array(
        "column" => "salary",
        "conditions" => "area = 'Sales'"
    )
);

Max/Min examples:

<?php

// What is the oldest age of all employees?
$age = Employees::maximum(array("column" => "age"));

// What is the oldest of employees from the Sales area?
$age = Employees::maximum(
    array(
        "column" => "age",
        "conditions" => "area = 'Sales'"
    )
);

// What is the lowest salary of all employees?
$salary = Employees::minimum(array("column" => "salary"));
缓存结果集

频繁访问数据库往往是WEB应用性能方面最常见的瓶颈之一。这是由于复杂的连接过程,PHP必须在每个请求都从数据库获取数据。一个较完善的技术架构是,将不经常改变的结果集缓存到系统中可以更快访问的地方(通常是内存)。

Phalcon\Mvc\Model 需要缓存结果集时,它会依赖于容器中的”modelsCache”这个服务。

Phalcon提供了一个组件缓存任何类型的数据,我们下面将介绍它如何与模型一块工作。首先,你需要把它作为一个服务注册到服务容器中:

<?php

//Set the models cache service
$di->set('modelsCache', function(){

    //Cache data for one day by default
    $frontCache = new Phalcon\Cache\Frontend\Data(array(
        "lifetime" => 86400
    ));

    //Memcached connection settings
    $cache = new Phalcon\Cache\Backend\Memcached($frontCache, array(
        "host" => "localhost",
        "port" => "11211"
    ));

    return $cache;
});

你可以创建和自定义缓存规则,然后作为一个匿名函数使用它们。一量缓存被正确设置,可以按如下方式缓存结果集:

<?php

// Get products without caching
$products = Products::find();

// Just cache the resultset. The cache will expire in 1 hour (3600 seconds)
$products = Products::find(array("cache" => true));

// Cache the resultset only for 5 minutes
$products = Products::find(array("cache" => 300));

// Cache the resultset with a key pre-defined
$products = Products::find(array("cache" => array("key" => "my-products-key")));

// Cache the resultset with a key pre-defined and for 2 minutes
$products = Products::find(
    array(
        "cache" => array(
            "key"      => "my-products-key",
            "lifetime" => 120
        )
    )
);

// Using a custom cache
$products = Products::find(array("cache" => $myCache));

默认情况下,Phalcon\Mvc\Model 将创建一个唯一的KEY来保存结果集数据,它使用md5 hash内部SQL语句的方式来生成唯一KEY,这将是非常实用的,因为它会产生一个新的唯一的KEY值。如果你想改变KEY值,你可以像上面的示例一样随时使用key参数进行指定,getLastKey()方法检索最后的缓存KEY值,这样就可以从缓存中定位和检索结果集:

<?php

// Cache the resultset using an automatic key
$products = Products::find(array("cache" => 3600));

// Get last generated key
$automaticKey = $products->getCache()->getLastKey();

// Use resultset as normal
foreach($products as $product){
    //...
}

缓存的KEY是通过 Phalcon\Mvc\Model 自动生成的,而且问题以”phc”为前辍,这将有助于识别此类缓存KEY是与 Phalcon\Mvc\Model 相关的:

<?php

// Set the cache to the models manager
$cache = $di->getModelsCache();

// Get keys created by Phalcon\Mvc\Model
foreach ($cache->queryKeys("phc") as $key) {
     echo $key, "\n";
}

请注意,并非所有的结果集都必须被缓存。变化非常频繁的结果不应该被缓存起来,因为在这种情况下他们是无效的,而且会影响性能。此外,不经常更改的大数据集可以被缓存,但是否一定需要缓存得衡量一下,不对性能造成一定的影响,还是可以按受的。

同样,缓存系统也可以应用于使用关联关系生成的结果集:

<?php

// Query some post
$post = Post::findFirst();

// Get comments related to a post, also cache it
$comments = $post->getComments(array("cache" => true));

// Get comments related to a post, setting lifetime
$comments = $post->getComments(array("cache" => true, "lifetime" => 3600));

当获取缓存结果集失败时,你可以简单的通过它的KEY值从缓存系统中删除它。

Creating Updating/Records

Phalcon\Mvc\Model::save() 方法允许你创建/更新记录。save方法自动调用 Phalcon\Mvc\Model 内部的create和update方法,如果想达到预期般的工作效果,正确定义实体主键是非常必须的,以确保创建和更新记录成功。

同时,方法的执行关联到 validators,虚拟外键以及在模型中定义的事件:

<?php

$robot       = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
if ($robot->save() == false) {
    echo "Umh, We can't store robots right now: \n";
    foreach ($robot->getMessages() as $message) {
        echo $message, "\n";
    }
} else {
    echo "Great, a new robot was saved successfully!";
}

save方法还可以直接通过传入一个数组的形式进行保存数据,Phalcon\Mvc\Model 会自动完成数组和对象的绑定的,而不需要直接指定对象的属性值:

<?php

$robot = new Robots();
$robot->save(array(
    "type" => "mechanical",
    "name" => "Astro Boy",
    "year" => 1952
));

数据直接赋值或通过数组绑定,这些数据都会根据相关的数据类型被escaped/sanitized,所以你可以传递一个不安全的数组,而不必担心发生SQL注入:

<?php

$robot = new Robots();
$robot->save($_POST);
Create/Update with Certainty

当一个应用程序有很多的竞争的时候,也许我们希望创建一个记录,但实际上是更新一个记录(想不到老外也搞作孽,哈哈)。如果我们使用Phalcon\Mvc\Model::save()保存数据到数据库,首先我们得确定我们的记录是将被创建还是更新:

<?php

$robot       = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;

//This record only must be created
if ($robot->create() == false) {
    echo "Umh, We can't store robots right now: \n";
    foreach ($robot->getMessages() as $message) {
        echo $message, "\n";
    }
} else {
    echo "Great, a new robot was created successfully!";
}

方法”create”和”update”都接受数组作为参数.

Auto-generated identity columns

有些模型可能有标识列。这些列通常是映射数据表的主键。 Phalcon\Mvc\Model 可以识别标识列,同时会忽略它内部的SQL INSERT,所以数据库系统能够生成一个自动生成的值。在创建一个记录后,标识列总是会通过数据库系统产生一个值:

<?php

$robot->save();
echo "The generated id is: ", $robot->id;

Phalcon\Mvc\Model 能够识别标识列。根据不同的数据库系统,这些列可能是串行列,例如PostgreSQL以及MYSQL的auto_increment列。

PostgreSQL使用序列来生成自动的数值,默认情况下,Phalcon试图多序列table_field_seq来获得生成的值,例如:robots_id_seq,如果该序列具有不同的名称,”getSequenceName”方法需要明确指定:

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function getSequenceName()
    {
        return "robots_sequence_name";
    }

}
Validation Messages

Phalcon\Mvc\Model 有一个消息传递子系统,它提供了一个灵活的输出方式,或存储在insert/update过程中的验证消息。

每个消息都是类 Phalcon\Mvc\Model\Message 的一个实例对象。生成的该组消息可以通过getMessages()方法来获取。每个消息都提供了扩展的信息,如字段名称,同时产生了消息及消息类型:

<?php

if ($robot->save() == false) {
    foreach ($robot->getMessages() as $message) {
        echo "Message: ", $message->getMessage();
        echo "Field: ", $message->getField();
        echo "Type: ", $message->getType();
    }
}

Phalcon\Mvc\Model 也可以产生以下类型的验证消息:

Type Description
PresenceOf Generated when a field with a non-null attribute on the database is trying to insert/update a null value
ConstraintViolation Generated when a field part of a virtual foreign key is trying to insert/update a value that doesn’t exist in the referenced model
InvalidValue Generated when a validator failed because of an invalid value
验证事件及事件管理

模型允许你实现事件,当执行insert和update的时候,这些事件将被抛出。他们帮助你定义业务规则。以下是 Phalcon\Mvc\Model 支持的事件以及他们的执行顺序:

Operation Name Can stop operation? Explanation
Inserting/Updating beforeValidation YES Is executed before the fields are validated for not nulls or foreign keys
Inserting beforeValidationOnCreate YES Is executed before the fields are validated for not nulls or foreign keys when an insertion operation is being made
Updating beforeValidationOnUpdate YES Is executed before the fields are validated for not nulls or foreign keys when an updating operation is being made
Inserting/Updating onValidationFails YES (already stopped) Is executed after an integrity validator fails
Inserting afterValidationOnCreate YES Is executed after the fields are validated for not nulls or foreign keys when an insertion operation is being made
Updating afterValidationOnUpdate YES Is executed after the fields are validated for not nulls or foreign keys when an updating operation is being made
Inserting/Updating afterValidation YES Is executed after the fields are validated for not nulls or foreign keys
Inserting/Updating beforeSave YES Runs before the required operation over the database system
Updating beforeUpdate YES Runs before the required operation over the database system only when an updating operation is being made
Inserting beforeCreate YES Runs before the required operation over the database system only when an inserting operation is being made
Updating afterUpdate NO Runs after the required operation over the database system only when an updating operation is being made
Inserting afterCreate NO Runs after the required operation over the database system only when an inserting operation is being made
Inserting/Updating afterSave NO Runs after the required operation over the database system

为了使模型对事件作出反应,我们必须实现一个方法具有相同名称的事件:

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function beforeValidationOnCreate()
    {
        echo "This is executed before create a Robot!";
    }

}

事件同样可以在执行一个操作之前做赋值操作,这将会很有用,下面是示例:

<?php

class Products extends \Phalcon\Mvc\Model
{

    public function beforeCreate()
    {
        //Set the creation date
        $this->created_at = date('Y-m-d H:i:s');
    }

    public function beforeUpdate()
    {
        //Set the modification date
        $this->modified_in = date('Y-m-d H:i:s');
    }

}

此外,该组件将与 Phalcon\Events\Manager 一同工作,这意味着当事件被触发时,我们可以创建监听器。

<?php

$eventsManager = new Phalcon\Events\Manager();

//Attach an anonymous function as a listener for "model" events
$eventsManager->attach('model', function($event, $robot) {
    if ($event->getType() == 'beforeSave') {
        if ($robot->name == 'Scooby Doo') {
            echo "Scooby Doo isn't a robot!";
            return false;
        }
    }
    return true;
});

$robot = new Robots();
$robot->setEventsManager($eventsManager);
$robot->name = 'Scooby Doo';
$robot->year = 1969;
$robot->save();

在上面的例子中,事件管理只是作为对象和监听器(匿名函数)之间的桥梁。如果我们想要在我们的应用程序中创建的所有对象使用相同的事件管理,那么我们就需要到指定的模型管理器:

<?php

//Registering the modelsManager service
$di->setShared('modelsManager', function() {

    $eventsManager = new Phalcon\Events\Manager();

    //Attach an anonymous function as a listener for "model" events
    $eventsManager->attach('model', function($event, $model){
        if (get_class($model) == 'Robots') {
            if ($event->getType() == 'beforeSave') {
                if ($modle->name == 'Scooby Doo') {
                    echo "Scooby Doo isn't a robot!";
                    return false;
                }
            }
        }
        return true;
    });

    //Setting a default EventsManager
    $modelsManager = new Phalcon\Mvc\Models\Manager();
    $modelsManager->setEventsManager($eventsManager);
    return $modelsManager;
});
Implementing a Business Rule

当执行insert,update或delete的时候,如果有任何方法名称与上表列出的事件名称相同,模型验证将起作用。

我们建议验证方法被声明为protected,以防止业务逻辑不被公开。

下面的示例实现验证在update或insert时,year不小于0的事件:

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function beforeSave()
    {
        if ($this->year < 0) {
            echo "Year cannot be smaller than zero!";
            return false;
        }
    }

}

有些事件返回false用于指示停止当前操作。如果一个事件没有返回任何东西,Phalcon\Mvc\Model 将假设它返回true。

Validating Data Integrity

Phalcon\Mvc\Model 提供了几个事件来验证数据,并实现业务规则。特殊的”validation”事件能使我们能够调用内置的验证器。Phalcon发布了一些内置的验证器,可用于在这个阶段的验证。

以下示例显示了如何使用它:

<?php

use Phalcon\Mvc\Model\Validator\InclusionIn;
use Phalcon\Mvc\Model\Validator\Uniqueness;

class Robots extends \Phalcon\Mvc\Model
{

    public function validation()
    {

        $this->validate(new InclusionIn(
            array(
                "field"  => "type",
                "domain" => array("Mechanical", "Virtual")
            )
        ));

        $this->validate(new Uniqueness(
            array(
                "field"   => "name",
                "message" => "The robot name must be unique"
            )
        ));

        return $this->validationHasFailed() != true;
    }

}

上面的例子中,使用内置的验证器“InclusionIn”执行验证。检查值在域列表中的“type”。如果该值没有被包括在该方法中,那么验证程序将失败并返回false。下列内置的验证器是可用的:

Name Explanation Example
PresenceOf Validates that a field’s value isn’t null or empty string. This validator is automatically added based on the attributes marked as not null on the mapped table Example
Email Validates that field contains a valid email format Example
ExclusionIn Validates that a value is not within a list of possible values Example
InclusionIn Validates that a value is within a list of possible values Example
Numericality Validates that a field has a numeric format Example
Regex Validates that the value of a field matches a regular expression Example
Uniqueness Validates that a field or a combination of a set of fields are not present more than once in the existing records of the related table Example
StringLength Validates the length of a string Example

除了使用这些内置验证器,你还可以创建你自己的验证器:

<?php

use \Phalcon\Mvc\Model\Validator,
    \Phalcon\Mvc\Model\ValidatorInterface;

class UrlValidator extends Validator implements ValidatorInterface
{

    public function validate($model)
    {
        $field = $this->getOption('field');

        $value = $model->$field;
        $filtered = filter_var($value, FILTER_VALIDATE_URL);
        if (!$filtered) {
            $this->appendMessage("The URL is invalid", $field, "UrlValidator");
            return false;
        }
        return true;
    }

}

把你编写的验证器绑定到模型上:

<?php

class Customers extends \Phalcon\Mvc\Model
{

    public function validation()
    {
        $this->validate(new UrlValidator(
            array(
                "field"  => "url",
            )
        ));
        if ($this->validationHasFailed() == true) {
            return false;
        }
    }

}

创建自定义验证器,主要想法是让他们可以在不同的模型中使用,即代码复用。一个验证器也可以按以下方式实现:

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function validation()
    {
        if ($this->type == "Old") {
            $message = new Phalcon\Mvc\Model\Message(
                "Sorry, old robots are not allowed anymore",
                "type",
                "MyType"
            );
            $this->appendMessage($message);
            return false;
        }
        return true;
    }

}
避免SQL注入攻击

每个被赋值到模型属性上的值在保存到数据库之前都将按照数据类型被转义,开发人员不需要手工转义每个值。Phalcon内部使用 bound parameters PDO提供转义。

mysql> desc products;
+------------------+------------------+------+-----+---------+----------------+
| Field            | Type             | Null | Key | Default | Extra          |
+------------------+------------------+------+-----+---------+----------------+
| id               | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| product_types_id | int(10) unsigned | NO   | MUL | NULL    |                |
| name             | varchar(70)      | NO   |     | NULL    |                |
| price            | decimal(16,2)    | NO   |     | NULL    |                |
| active           | char(1)          | YES  |     | NULL    |                |
+------------------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

如果我们只使用PDO来安全的存储一条记录,我们需要编写以下代码:

<?php

$productTypesId = 1;
$name = 'Artichoke';
$price = 10.5;
$active = 'Y';

$sql = 'INSERT INTO products VALUES (null, :productTypesId, :name, :price, :active)';
$sth = $dbh->prepare($sql);

$sth->bindParam(':productTypesId', $productTypesId, PDO::PARAM_INT);
$sth->bindParam(':name', $name, PDO::PARAM_STR, 70);
$sth->bindParam(':price', doubleval($price));
$sth->bindParam(':active', $active, PDO::PARAM_STR, 1);

$sth->execute();

好消息是,Phalcon自动为您做到这一点:

<?php

$product = new Products();
$product->product_types_id = 1;
$product->name = 'Artichoke';
$product->price = 10.5;
$product->active = 'Y';
$product->create();

Skipping Columns

有时候,有一些数据使用数据库系统的触发器或默认值,因此我们在insert/update的时候,会忽略掉这些属性:

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        //Skips fields/columns on both INSERT/UPDATE operations
        $this->skipAttributes(array('year', 'price'));

        //Skips only when inserting
        $this->skipAttributesOnCreate(array('created_at'));

        //Skips only when updating
        $this->skipAttributesOnUpdate(array('modified_in'));
    }

}

这时,在整个应用程序中执行insert/update的时候,都会忽略这些值的传递。 强制一个默认值,可以以下列方式进行:

<?php

$robot = new Robots();
$robot->name = 'Bender';
$robot->year = 1999;
$robot->created_at = new Phalcon\Db\RawValue('default');
$robot->create();

删除记录

Phalcon\Mvc\Model::delete() 允许删除一条记录,你可以按如下方式使用:

<?php

$robot = Robots::findFirst(11);
if ($robot != false) {
    if ($robot->delete() == false) {
        echo "Sorry, we can't delete the robot right now: \n";
        foreach ($robot->getMessages() as $message) {
            echo $message, "\n";
        }
    } else {
        echo "The robot was deleted successfully!";
    }
}

你也可以通过使用foreach遍历一个结果集的方式删除多条记录:

<?php

foreach (Robots::find("type='mechanical'") as $robot) {
    if ($robot->delete() == false) {
        echo "Sorry, we can't delete the robot right now: \n";
        foreach ($robot->getMessages() as $message) {
            echo $message, "\n";
        }
    } else {
        echo "The robot was deleted successfully!";
    }
}

当执行一个删除操作时,你可以使用以下事件定义一个自定义的业务规则:

Operation Name Can stop operation? Explanation
Deleting beforeDelete YES Runs before the delete operation is made
Deleting afterDelete NO Runs after the delete operation was made

Validation Failed Events

另一种类型的事件是,当你验证数据过程中发现任何不一致时:

Operation Name Explanation
Insert or Update notSave Triggered when the INSERT or UPDATE operation fails for any reason
Insert, Delete or Update onValidationFails Triggered when any data manipulation operation fails

事务管理(Transactions)

当一个进程执行多个数据库操作时,如果要保证数据的完整性,那么它每个步骤的执行都必须保证是成功的。事务提供了在数据被提交到数据库之前,保证所有数据库操作被成功执行的能力。

在Phalcon中,事务允许你提交所有操作,如果出现了错误,你可以回滚所有的操作。

<?php

try {

    //Create a transaction manager
    $manager = new Phalcon\Mvc\Model\Transaction\Manager();

    // Request a transaction
    $transaction = $manager->get();

    $robot = new Robots();
    $robot->setTransaction($transaction);
    $robot->name = "WALL·E";
    $robot->created_at = date("Y-m-d");
    if ($robot->save() == false) {
        $transaction->rollback("Cannot save robot");
    }

    $robotPart = new RobotParts();
    $robotPart->setTransaction($transaction);
    $robotPart->type = "head";
    if ($robotPart->save() == false) {
        $transaction->rollback("Cannot save robot part");
    }

    //Everything goes fine, let's commit the transaction
    $transaction->commit();

} catch(Phalcon\Mvc\Model\Transaction\Failed $e) {
    echo "Failed, reason: ", $e->getMessage();
}

Transactions can be used to delete many records in a consistent way:

<?php

use Phalcon\Mvc\Model\Transaction\Manager as Tx,
    Phalcon\Mvc\Model\Transaction\Failed as TxFailed;

try {

    //Create a transaction manager
    $manager = new Tx();

    //Request a transaction
    $transaction = $manager->get();

    //Get the robots will be deleted
    foreach (Robots::find("type='mechanical'") as $robot) {
        $robot->setTransaction($transaction);
        if ($robot->delete() == false) {
            //Something goes wrong, we should to rollback the transaction
            foreach ($robot->getMessages() as $message) {
                $transaction->rollback($message->getMessage());
            }
        }
    }

    //Everything goes fine, let's commit the transaction
    $transaction->commit();

    echo "Robots were deleted successfully!";

} catch(TxFailed $e) {
    echo "Failed, reason: ", $e->getMessage();
}

事务总是被重复使用。我们希望只有当commit()或rollback()被执行的时候,才会产生一个事务的实例,你可以把事务注册为整个应用程序的一个服务,当作一个整体的事务管理器使用:

<?php

$di->setShared('transactions', function(){
    return new Phalcon\Mvc\Model\Transaction\Manager();
});

然后我们可以在控制器和视图中直接访问它:

<?php

class ProductsController extends \Phalcon\Mvc\Controller {

    public function saveAction()
    {

        //Obtain the TransactionsManager from the DI container
        $manager = $this->di->getTransactions();

        //Request a transaction
        $transaction = $manager->get();

    }

}

Independent Column Mapping

ORM支持独立的列映射,它允许开发人员在模型中的属性不同于数据库的字段名称。Phalcon能够识别新的列名,并会相应的进行重命名,以对应数据库中的字段。 这是一个伟大的功能,当你需要重命名数据库中的字段,而不必担心代码中所有的查询。示例如下:

<?php

class Robots extends Phalcon\Mvc\Model
{

    public function columnMap()
    {
        //Keys are the real names in the table and
        //the values their names in the application
        return array(
            'id' => 'code',
            'the_name' => 'theName',
            'the_type' => 'theType',
            'the_year' => 'theYear'
        );
    }

}

然后你就可以在你的代码中理所当然的使用新的属性名称:

<?php

//Find a robot by its name
$robot = Robots::findFirst("theName = 'Voltron'");
echo $robot->theName, "\n";

//Get robots ordered by type
$robot = Robots::find(array('order' => 'theType DESC'));
foreach ($robots as $robot) {
    echo 'Code: ', $robot->code, "\n";
}

//Create a robot
$robot = new Robots();
$robot->code = '10101';
$robot->theName = 'Bender';
$robot->theType = 'Industrial';
$robot->theYear = 2999;
$robot->save();

当有下面的情况时,你可以考虑使用新的别名:

  • 在relationships/validators中,必须使用新的名称
  • 列名会导致ORM的异常发生

Models Meta-Data

为了加快开发 Phalcon\Mvc\Model 帮助你从数据表中查询字段以及查询数据库的约束。要做到这一点,Phalcon\Mvc\Model\MetaData 用于管理和缓存这些元数据。

有时,需要使用模型获取那些元数据的,你可以通过以下示例获得:

<?php

$robot = new Robots();

// Get Phalcon\Mvc\Model\Metadata instance
$metaData = $robot->getDI()->getModelsMetaData();

// Get robots fields names
$attributes = $metaData->getAttributes($robot);
print_r($attributes);

// Get robots fields data types
$dataTypes = $metaData->getDataTypes($robot);
print_r($dataTypes);
Caching Meta-Data

应用程序在一个生产阶段时,没有必要总是从数据库系统中查询元数据,你可以使用以下的几种适配器把这些元数据缓存起来:

Adapter Description API
Memory This adapter is the default. The meta-data is cached only during the request. When the request is completed, the meta-data are released as part of the normal memory of the request. This adapter is perfect when the application is in development so as to refresh the meta-data in each request containing the new and/or modified fields. Phalcon\Mvc\Model\MetaData\Memory
Session This adapter stores meta-data in the $_SESSION superglobal. This adapter is recommended only when the application is actually using a small number of models. The meta-data are refreshed every time a new session starts. This also requires the use of session_start() to start the session before using any models. Phalcon\Mvc\Model\MetaData\Session
Apc The Apc adapter uses the Alternative PHP Cache (APC) to store the table meta-data. You can specify the lifetime of the meta-data with options. This is the most recommended way to store meta-data when the application is in production stage. Phalcon\Mvc\Model\MetaData\Apc
Files This adapter uses plain files to store meta-data. By using this adapter the disk-reading is increased but the database access is reduced Phalcon\Mvc\Model\MetaData\Files

作为其他ORM的依赖,元数据需要从服务容器中获得:

<?php

$di->setShared('modelsMetadata', function() {

    // Create a meta-data manager with APC
    $metaData = new Phalcon\Mvc\Model\MetaData\Apc(
        array(
            "lifetime" => 86400,
            "suffix"   => "my-suffix"
        )
    );

    return $metaData;
});
Manual Meta-Data

Phalcon可以自动的获得元数据,不强制开发人员必须手工设定他们。 请注意,手工定义元数据时,添加/修改/删除 数据表字段的时候,必须手工添加/修改/删除 元数据对应列,以保证一切正常工作。

下面的例子演示了如何手工定义元数据:

<?php

use Phalcon\Mvc\Model\MetaData;
use Phalcon\Db\Column;

class Robots extends Phalcon\Mvc\Model
{

    public function metaData()
    {
        return array(

            //Every column in the mapped table
            MetaData::MODELS_ATTRIBUTES => array(
                'id', 'name', 'type', 'year'
            ),

            //Every column part of the primary key
            MetaData::MODELS_PRIMARY_KEY => array(
                'id'
            ),

            //Every column that isn't part of the primary key
            MetaData::MODELS_NON_PRIMARY_KEY => array(
                'name', 'type', 'year'
            ),

            //Every column that doesn't allows null values
            MetaData::MODELS_NOT_NULL => array(
                'id', 'name', 'type', 'year'
            ),

            //Every column and their data types
            MetaData::MODELS_DATA_TYPES => array(
                'id' => Column::TYPE_INTEGER,
                'name' => Column::TYPE_VARCHAR,
                'type' => Column::TYPE_VARCHAR,
                'year' => Column::TYPE_INTEGER
            ),

            //The columns that have numeric data types
            MetaData::MODELS_DATA_TYPES_NUMERIC => array(
                'id' => true,
                'year' => true,
            ),

            //The identity column
            MetaData::MODELS_IDENTITY_COLUMN => 'id',

            //How every column must be bound/casted
            MetaData::MODELS_DATA_TYPES_BIND => array(
                'id' => Column::BIND_PARAM_INT,
                'name' => Column::BIND_PARAM_STR,
                'type' => Column::BIND_PARAM_STR,
                'year' => Column::BIND_PARAM_INT,
            ),

            //Fields that must be ignored from INSERT/UPDATE SQL statements
            MetaData::MODELS_AUTOMATIC_DEFAULT => array('year')

        );
    }

}

Pointing to a different schema

如果模型映射的表不是默认的schemas/databases,你可以通过 getSchema 方法手工指定它:

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function getSchema()
    {
        return "toys";
    }

}

建立多个数据库连接

在Phalcon中,所有的模型都属于一个数据库连接,实际上,当 Phalcon\Mvc\Model 需要连接数据库时,它请求服务容器中的”db”服务,在initialize方法中,您可以覆盖此服务:

<?php

//This service returns a MySQL database
$di->set('dbMysql', function() {
     return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "root",
        "password" => "secret",
        "dbname" => "invo"
    ));
});

//This service returns a PostgreSQL database
$di->set('dbPostgres', function() {
     return new \Phalcon\Db\Adapter\Pdo\PostgreSQL(array(
        "host" => "localhost",
        "username" => "postgres",
        "password" => "",
        "dbname" => "invo"
    ));
});

然后,在模型的Initialize方法中,我们可以通过以下方式访问一个数据库连接:

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->setConnectionService('dbPostgres');
    }

}

记录SQL日志

当使用高层次的抽象组件,比如 Phalcon\Mvc\Model 访问数据库时,很难理解这些语句最终发送到数据库时是什么样的。 Phalcon\Mvc\Model 内部由 Phalcon\Db 支持。Phalcon\LoggerPhalcon\Db 交互工作,可以提供数据库抽象层的日志记录功能,从而使我们能够记录下SQL语句。

<?php

$di->set('db', function() {

    $eventsManager = new Phalcon\Events\Manager();

    $logger = new Phalcon\Logger\Adapter\File("app/logs/debug.log");

    //Listen all the database events
    $eventsManager->attach('db', function($event, $connection) use ($logger) {
        if ($event->getType() == 'beforeQuery') {
            $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
        }
    });

    $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "root",
        "password" => "secret",
        "dbname" => "invo"
    ));

    //Assign the eventsManager to the db adapter instance
    $connection->setEventsManager($eventsManager);

    return $connection;
});

当模型访问默认的数据库连接时,所有的SQL语句都会被记录在该文件中:

<?php

$robot = new Robots();
$robot->name = "Robby the Robot";
$robot->created_at = "1956-07-21"
if ($robot->save() == false) {
    echo "Cannot save robot";
}

如上文所述,文件 app/logs/db.log 包含这样的内容:

[Mon, 30 Apr 12 13:47:18 -0500][DEBUG][Resource Id #77] INSERT INTO robots
(name, created_at) VALUES ('Robby the Robot', '1956-07-21')

剖析SQL语句

感谢 Phalcon\Db ,作为 Phalcon\Mvc\Model 的基本组成部分,剖析ORM产生的SQL语句变得可能,以便分析数据库的性能问题,同时你可以诊断性能问题,并发现瓶颈。

<?php

$di->set('profiler', function(){
    return new Phalcon\Db\Profiler();
});

$di->set('db', function() use ($di) {

    $eventsManager = new Phalcon\Events\Manager();

    //Get a shared instance of the DbProfiler
    $profiler = $di->getProfiler();

    //Listen all the database events
    $eventsManager->attach('db', function($event, $connection) use ($profiler) {
        if ($event->getType() == 'beforeQuery') {
            $profiler->startProfile($connection->getSQLStatement());
        }
        if ($event->getType() == 'afterQuery') {
            $profiler->stopProfile();
        }
    });

    $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "root",
        "password" => "secret",
        "dbname" => "invo"
    ));

    //Assign the eventsManager to the db adapter instance
    $connection->setEventsManager($eventsManager);

    return $connection;
});

Profiling some queries:

<?php

// Send some SQL statements to the database
Robots::find();
Robots::find(array("order" => "name");
Robots::find(array("limit" => 30);

//Get the generated profiles from the profiler
$profiles = $di->getShared('profiler')->getProfiles();

foreach ($profiles as $profile) {
   echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
   echo "Start Time: ", $profile->getInitialTime(), "\n";
   echo "Final Time: ", $profile->getFinalTime(), "\n";
   echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";
}

每个生成的profile文件,都是以毫秒为单位。

Injecting services into Models

你可能需要在模型中访问服务容器的一个服务,下面的示例将为你展示如何使用:

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function notSave()
    {
        //Obtain the flash service from the DI container
        $flash = $this->getDI()->getFlash();

        //Show validation messages
        foreach ($this->getMesages() as $message) {
            $flash->error((string) $message);
        }
    }

}

“create”或”update”操作失败的时候,”notSave”事件总是被触发,所以我们通过访问服务容器中的”flash”服务来输出验证消息。

Phalcon Query Language (PHQL)

译者注:学过JAVA,略懂Hibernate的人应该会知道,hibernate是javaee中一个非常流程的ORM软件,它其中生成的中间语句就叫做HQL。

Phalcon查询语言,也可以叫PhalconQL或PHQL,是一个高层次的,允许你使用一种类SQL语言的方式的一种SQL方言。PHQL是一个用C语言编写的SQL语法分析器。

为了达到尽可能高的性能,Phalcon提供了一个分析器,使用了和 SQLite 相同的技术。该技术提供了一个小型的内存分析器,具有非常低的内存占用,同时也是线程安全的。

解析器首先检查传递过来的PHQL语句,然后把它们转化成一种中间性的语句,最后再将其转换为相应的RDBMS所需要的SQL方言。

在PHQL中,我们已经实现了一系列的功能,以保证你在访问数据库时是安全的:

  • Bound parameters are part of the PHQL language helping you to secure your code
  • PHQL only allows one SQL statement to be executed per call preventing injections
  • PHQL ignores all SQL comments which are often used in SQL injections
  • PHQL only allows data manipulation statements, avoiding altering or dropping tables/databases by mistake or externally without authorization
  • PHQL implements a high level abstraction allowing you handling models as tables and class attributes as fields

使用示例

为了更好的展示PHQL是如何工作的,我们将使用模型 “Cars” 和 “Brands”:

<?php

class Cars extends Phalcon\Mvc\Model
{
    public $id;

    public $name;

    public $brand_id;

    public $price;

    public $year;

    public $style;

   /**
    * This model is mapped to the table sample_cars
    */
    public function getSource()
    {
        return 'sample_cars';
    }

    /**
     * A car only has a Brand, but a Brand have many Cars
     */
    public function initialize()
    {
        $this->belongsTo('brand_id', 'Brands', 'id');
    }
}

每个Car只有一个Brand,一个Brand有多个Cars:

<?php

class Brands extends Phalcon\Mvc\Model
{

    public $id;

    public $name;

    /**
     * The model Brands is mapped to the "sample_brands" table
     */
    public function getSource()
    {
        return 'sample_brands';
    }

    /**
     * A Brand can have many Cars
     */
    public function initialize()
    {
        $this->hasMany('id', 'Cars', 'brand_id');
    }
}

Creating PHQL Queries

PHQL查询可以通过实例化 Phalcon\Mvc\Model\Query 来创建:

<?php

// Instantiate the Query
$query = new Phalcon\Mvc\Model\Query("SELECT * FROM Cars");

// Pass the DI container
$query->setDI($di);

// Execute the query returning a result if any
$robots = $query->execute();

在控制器或视图文件中,它可以使用服务容器中的一个注入服务 models manager 来轻松的实现create/execute

<?php

$query = $this->modelsManager->createQuery("SELECT * FROM Cars");

$robots = $query->execute();

或者像下面这样:

<?php

$robots = $this->modelsManager->executeQuery("SELECT * FROM Cars");

Selecting Records

作为大家所熟悉的SQL,PHQL允许你在查询中使用SELECT语句,只是需要使用模型类的名称来替代数据表名:

<?php

$query = $manager->createQuery("SELECT * FROM Cars ORDER BY Cars.name");
$query = $manager->createQuery("SELECT Cars.name FROM Cars ORDER BY Cars.name");

带有命名空间的模型类同样可以:

<?php

$phql = "SELECT * FROM Formula\Cars ORDER BY Formula\Cars.name";
$query = $manager->createQuery($phql);

$phql = "SELECT Formula\Cars.name FROM Formula\Cars ORDER BY Formula\Cars.name";
$query = $manager->createQuery($phql);

$phql = "SELECT c.name FROM Formula\Cars c ORDER BY c.name";
$query = $manager->createQuery($phql);

Phalcon支持大部分的SQL标准,甚至是非标准指令,如,LIMIT:

<?php

$phql   = "SELECT c.name FROM Cars AS c "
   . "WHERE c.brand_id = 21 ORDER BY c.name LIMIT 100";
$query = $manager->createQuery($phql);
Results Types

根据我们查询列的类型,返回的结果类型会稍有不同。如果你检索一个整体对象,它将返回 Phalcon\Mvc\Model\Resultset\Simple 的对象实例。这种结果集是一组完整的模型对象:

<?php

$phql = "SELECT c.* FROM Cars AS c ORDER BY c.name";
$cars = $manager->executeQuery($phql);
foreach ($cars as $car)
{
    echo "Name: ", $car->name, "\n";
}

这是完全一样的:

<?php

$cars = Cars::find(array("order" => "name"));
foreach ($cars as $car)
{
    echo "Name: ", $car->name, "\n";
}

完整的对象可以被修改和重新保存到数据库,因为他们代表着关联数据表的一个完整记录。有一些其他类型的查询不返回完整的对象,例如:

<?php

$phql = "SELECT c.id, c.name FROM Cars AS c ORDER BY c.name";
$cars = $manager->executeQuery($phql);
foreach ($cars as $car)
{
    echo "Name: ", $car->name, "\n";
}

我们只查询了数据表中的某些字段,因此,这不能算是一个完整的对象。在这种情况下,也返回 Phalcon\Mvc\Model\Resultset\Simple 的实例对象。然而,这个对象只包含两列属性值。

这些值不代表完整的对象,我们称他们为标量。PHQL允许你查询各种类型的标量,如fields,functions,literals, expressions等

<?php

$phql = "SELECT CONCAT(c.id, ' ', c.name) AS id_name FROM Cars AS c ORDER BY c.name";
$cars = $manager->executeQuery($phql);
foreach ($cars as $car)
{
    echo $car->id_name, "\n";
}

我们既可以只查询完整的对象或标量,也可以同时查询他们:

<?php

$phql   = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c ORDER BY c.name";
$result = $manager->executeQuery($phql);

在这种情况下,返回的是 Phalcon\Mvc\Model\Resultset\Complex 的实例对象,这允许同时访问完整对象和标量:

<?php

foreach ($result as $row)
{
    echo "Name: ", $row->cars->name, "\n";
    echo "Price: ", $row->cars->price, "\n";
    echo "Taxes: ", $row->taxes, "\n";
}

标量的属性值映射到”row”上,而完整的对象则是被映射到与它相关的模型对象上。

Joins

使用PHQL可以很方便的通过多个模型来获取数据,Phalcon支持大多数类型的Joins。我们在模型中定义的关系,在使用PHQL时会自动的添加到条件上:

<?php

$phql  = "SELECT Cars.name AS car_name, Brands.name AS brand_name FROM Cars JOIN Brands";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row)
{
    echo $row->car_name, "\n";
    echo $row->brand_name, "\n";
}

默认情况下,将使用INNER JOIN的方式,你也可以在查询中使用其他类型的JOIN:

<?php

$phql = "SELECT Cars.*, Brands.* FROM Cars INNER JOIN Brands";
$rows = $manager->executeQuery($phql);

$phql = "SELECT CCars.*, Brands.* FROM Cars LEFT JOIN Brands";
$rows = $manager->executeQuery($phql);

$phql = "SELECT Cars.*, Brands.* FROM Cars LEFT OUTER JOIN Brands";
$rows = $manager->executeQuery($phql);

$phql = "SELECT Cars.*, Brands.* FROM Cars CROSS JOIN Brands";
$rows = $manager->executeQuery($phql);

有可能的话,在JOIN中手工设置SQL条件:

<?php

$phql = "SELECT Cars.*, Brands.* FROM Cars INNER JOIN Brands ON Brands.id = Cars.brands_id";
$rows = $manager->executeQuery($phql);

同时,Joins还可以在使用以下方式:

<?php

$phql = "SELECT Cars.*, Brands.* FROM Cars, Brands WHERE Brands.id = Cars.brands_id";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row)
{
    echo "Car: ", $row->cars->name, "\n";
    echo "Brand: ", $row->brands->name, "\n";
}

如果在查询时使用了别名,获取属性值将使用别名的名称做为row的名称:

<?php

$phql = "SELECT c.*, b.* FROM Cars c, Brands b WHERE b.id = c.brands_id";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row)
{
    echo "Car: ", $row->c->name, "\n";
    echo "Brand: ", $row->b->name, "\n";
}
Aggregations

下面的示例将展示如何在PHQL中使用聚合:

<?php

// How much are the prices of all the cars?
$phql = "SELECT SUM(price) AS summatory FROM Cars";
$row  = $manager->executeQuery($phql)->getFirst();
echo $row['summatory'];

// How many cars are by each brand?
$phql = "SELECT Cars.brand_id, COUNT(*) FROM Cars GROUP BY Cars.brand_id";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row)
{
    echo $row->brand_id, ' ', $row["1"], "\n";
}

// How many cars are by each brand?
$phql = "SELECT Brands.name, COUNT(*) FROM Cars JOIN Brands GROUP BY 1";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row)
{
    echo $row->name, ' ', $row["1"], "\n";
}

$phql = "SELECT MAX(price) AS maximum, MIN(price) AS minimum FROM Cars";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row)
{
    echo $row["maximum"], ' ', $row["minimum"], "\n";
}

// Count distinct used brands
$phql = "SELECT COUNT(DISTINCT brand_id) AS brandId FROM Cars";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row)
{
    echo $row->brandId, "\n";
}
条件(Conditions)

条件的作用是允许你过滤查询内容,WHERE条件可以这样使用:

<?php

// Simple conditions
$phql = "SELECT * FROM Cars WHERE Cars.name = 'Lamborghini Espada'";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.price > 10000";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE TRIM(Cars.name) = 'Audi R8'";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.name LIKE 'Ferrari%'";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.name NOT LIKE 'Ferrari%'";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.price IS NULL";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.id IN (120, 121, 122)";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.id NOT IN (430, 431)";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.id BETWEEN 1 AND 100";
$cars = $manager->executeQuery($phql);

此外,PHQL的另一特点,prepared参数自动转义用户输入数据,下面将介绍的是与安全相关:

<?php

$phql = "SELECT * FROM Cars WHERE Cars.name = :name:";
$cars = $manager->executeQuery($phql, array("name" => 'Lamborghini Espada'));

$phql = "SELECT * FROM Cars WHERE Cars.name = ?0";
$cars = $manager->executeQuery($phql, array(0 => 'Lamborghini Espada'));

Inserting Data

PHQL是使用熟悉的INSERT语句插入数据:

<?php

// Inserting without columns
$phql = "INSERT INTO Cars VALUES (NULL, 'Lamborghini Espada', "
      . "7, 10000.00, 1969, 'Grand Tourer')";
$manager->executeQuery($phql);

// Specifyng columns to insert
$phql = "INSERT INTO Cars (name, brand_id, year, style) "
      . "VALUES ('Lamborghini Espada', 7, 1969, 'Grand Tourer')";
$manager->executeQuery($phql);

// Inserting using placeholders
$phql = "INSERT INTO Cars (name, brand_id, year, style) "
      . "VALUES (:name:, :brand_id:, :year:, :style)";
$manager->executeQuery($sql,
    array(
        'name'     => 'Lamborghini Espada',
        'brand_id' => 7,
        'year'     => 1969,
        'style'    => 'Grand Tourer',
    )
);

Phalcon中不只是用PHQL语句转换为SQL语句的。如果我们是手工创建模型对象,里面的所有事件及定义的业务规则都会被执行。现在,我们添加一个模型Cars的业务规则,让car的价格不低于$ 10,000:

<?php

use Phalcon\Mvc\Model\Message;

class Cars extends Phalcon\Mvc\Model
{

    public function beforeCreate()
    {
        if ($this->price < 10000)
        {
            $this->appendMessage(new Message("A car cannot cost less than $ 10,000"));
            return false;
        }
    }

}

如果我们在模型中使用以下的INSERT语句,INSERT操作将不成功,因为价格不符合定义的规则:

<?php

$phql   = "INSERT INTO Cars VALUES (NULL, 'Nissan Versa', 7, 9999.00, 2012, 'Sedan')";
$result = $manager->executeQuery($phql);
if ($result->success() == false)
{
    foreach ($result->getMessages() as $message)
    {
        echo $message->getMessage();
    }
}

更新数据(Updating Data)

更新一行记录和插入一行记录非常相似。正如你所知道的,更新数据记录的指令是UPDATE。当更新一行记录时,对应的模型事件将被执行。

<?php

// Updating a single column
$phql = "UPDATE Cars SET price = 15000.00 WHERE id = 101";
$manager->executeQuery($phql);

// Updating multiples columns
$phql = "UPDATE Cars SET price = 15000.00, type = 'Sedan' WHERE id = 101";
$manager->executeQuery($phql);

// Updating multiples rows
$phql = "UPDATE Cars SET price = 7000.00, type = 'Sedan' WHERE brands_id > 5";
$manager->executeQuery($phql);

// Using placeholders
$phql = "UPDATE Cars SET price = ?0, type = ?1 WHERE brands_id > ?2";
$manager->executeQuery(
    $phql,
    array(
        0 => 7000.00,
        1 => 'Sedan',
        2 => 5
    )
);

删除数据(Deleting Data)

当删除数据时,对应的模型事件将被执行:

<?php

// Deleting a single row
$phql = "DELETE FROM Cars WHERE id = 101";
$manager->executeQuery($phql);

// Deleting multiple rows
$phql = "DELETE FROM Cars WHERE id > 100";
$manager->executeQuery($phql);

// Using placeholders
$phql = "DELETE FROM Cars WHERE id BETWEEN :initial: AND :final:";
$manager->executeQuery(
    $phql,
    array(
        'initial' => 1,
        'final' => '100
    )
);

使用Query Builder创建queries(Creating queries using the Query Builder)

Query Builder可以创建一个PHQL query,而不需要编写PHQL语句了,同时Query Builder对IDE工具是友好的(可以自动提示):

<?php

$manager->createBuilder()
    >join('RobotsParts');
    ->limit(20);
    ->order('Robots.name')
    ->getQuery()
    ->execute();

与下面是相同的:

<?php

$phql = "SELECT Robots.*
    FROM Robots JOIN RobotsParts p
    ORDER BY Robots.name LIMIT 20";
$result = $manager->executeQuery($phql);

更多关于query builder的示例:

<?php

$builder->from('Robots')
// 'SELECT Robots.* FROM Robots'

// 'SELECT Robots.*, RobotsParts.* FROM Robots, RobotsParts'
$builder->from(array('Robots', 'RobotsParts'))

// 'SELECT * FROM Robots'
$phql = $builder->columns('*')
                ->from('Robots')

// 'SELECT id, name FROM Robots'
$builder->columns(array('id', 'name'))
        ->from('Robots')

// 'SELECT id, name FROM Robots'
$builder->columns('id, name')
        ->from('Robots')

// 'SELECT Robots.* FROM Robots WHERE Robots.name = "Voltron"'
$builder->from('Robots')
        ->where('Robots.name = "Voltron"')

// 'SELECT Robots.* FROM Robots WHERE Robots.id = 100'
$builder->from('Robots')
        ->where(100)

// 'SELECT Robots.* FROM Robots GROUP BY Robots.name'
$builder->from('Robots')
        ->groupBy('Robots.name')

// 'SELECT Robots.* FROM Robots GROUP BY Robots.name, Robots.id'
$builder->from('Robots')
        ->groupBy(array('Robots.name', 'Robots.id'))

// 'SELECT Robots.name, SUM(Robots.price) FROM Robots GROUP BY Robots.name'
$builder->columns(array('Robots.name', 'SUM(Robots.price)'))
    ->from('Robots')
    ->groupBy('Robots.name')

// 'SELECT Robots.name, SUM(Robots.price) FROM Robots
// GROUP BY Robots.name HAVING SUM(Robots.price) > 1000'
$builder->columns(array('Robots.name', 'SUM(Robots.price)'))
    ->from('Robots')
    ->groupBy('Robots.name')
    ->having('SUM(Robots.price) > 1000')

// 'SELECT Robots.* FROM Robots JOIN RobotsParts');
$builder->from('Robots')
    ->join('RobotsParts')

// 'SELECT Robots.* FROM Robots JOIN RobotsParts AS p');
$builder->from('Robots')
    ->join('RobotsParts', null, 'p')

// 'SELECT Robots.* FROM Robots JOIN RobotsParts ON Robots.id = RobotsParts.robots_id AS p');
$builder->from('Robots')
    ->join('RobotsParts', 'Robots.id = RobotsParts.robots_id', 'p')

// 'SELECT Robots.* FROM Robots
// JOIN RobotsParts ON Robots.id = RobotsParts.robots_id AS p
// JOIN Parts ON Parts.id = RobotsParts.parts_id AS t'
$builder->from('Robots')
    ->join('RobotsParts', 'Robots.id = RobotsParts.robots_id', 'p')
    ->join('Parts', 'Parts.id = RobotsParts.parts_id', 't')

// 'SELECT r.* FROM Robots AS r'
$builder->addFrom('Robots', 'r')

// 'SELECT Robots.*, p.* FROM Robots, Parts AS p'
$builder->from('Robots')
    ->addFrom('Parts', 'p')

// 'SELECT r.*, p.* FROM Robots AS r, Parts AS p'
$builder->from(array('r' => 'Robots'))
        ->addFrom('Parts', 'p')

// 'SELECT r.*, p.* FROM Robots AS r, Parts AS p');
$builder->from(array('r' => 'Robots', 'p' => 'Parts'))

// 'SELECT Robots.* FROM Robots LIMIT 10'
$builder->from('Robots')
    ->limit(10)

// 'SELECT Robots.* FROM Robots LIMIT 10 OFFSET 5'
$builder->from('Robots')
        ->limit(10, 5)

ODM (Object-Document Mapper)

In addition to its ability to map tables in relational databases, Phalcon can map documents from NoSQL databases. The ODM offers a CRUD functionality, events, validations among other services.

Due to the absence of SQL queries and planners, NoSQL databases can see real improvements in performance using the Phalcon approach. Additionally, there are no SQL building eliminating the possibility of SQL injections.

The following NoSQL databases are supported:

Name Description
MongoDB MongoDB is a scalable, high-performance, open source NoSQL database.

Creating Models

A model is a class that extends from Phalcon\Mvc\Collection. It must be placed in the models directory. A model file must contain a single class; its class name should be in camel case notation:

<?php

class Robots extends \Phalcon\Mvc\Collection
{

}
If you’re using PHP 5.4 is recommended declare each column that makes part of the model in order to save memory and reduce the memory allocation.

By default model “Robots” will refer to the collection “robots”. If you want to manually specify another name for the mapping collection, you can use the getSource() method:

<?php

class Robots extends \Phalcon\Mvc\Collection
{

    public function getSource()
    {
        return "the_robots";
    }

}

Understanding Documents To Objects

Every instance of a model represents a document in the collection. You can easily access collection data by reading object properties. For example, for a collection “robots” with the documents:

$ mongo test
MongoDB shell version: 1.8.2
connecting to: test
> db.robots.find()
{ "_id" : ObjectId("508735512d42b8c3d15ec4e1"), "name" : "Astro Boy", "year" : 1952,
        "type" : "mechanical" }
{ "_id" : ObjectId("5087358f2d42b8c3d15ec4e2"), "name" : "Bender", "year" : 1999,
        "type" : "mechanical" }
{ "_id" : ObjectId("508735d32d42b8c3d15ec4e3"), "name" : "Wall-E", "year" : 2008 }
>

Models in Namespaces

Namespaces can be used to avoid class name collision. In this case it is necessary to indicate the name of the related collection using getSource:

<?php

namespace Store\Toys;

class Robots extends \Phalcon\Mvc\Collection
{

    public function getSource()
    {
        return "robots";
    }

}

You could find a certain document by its id and then print its name:

<?php

// Find record with _id = "5087358f2d42b8c3d15ec4e2"
$robot = Robots::findById("5087358f2d42b8c3d15ec4e2");

// Prints "Bender"
echo $robot->name;

Once the record is in memory, you can make modifications to its data and then save changes:

<?php

$robot = Robots::findFirst(
    array(
        array('name' => 'Astroy Boy')
    )
);
$robot->name = "Voltron";
$robot->save();

Setting a Connection

Connections are retrieved from the services container. By default, Phalcon tries to find the connection in a service called “mongo”:

<?php

// Simple database connection to localhost
$di->set(
    'mongo',
    function()
    {
        $mongo = new Mongo();
        return $mongo->selectDb("store");
    }
);

// Connecting to a domain socket, falling back to localhost connection
$di->set(
    'mongo',
    function()
    {
        $mongo = new Mongo("mongodb:///tmp/mongodb-27017.sock,localhost:27017");
        return $mongo->selectDb("store");
    }
);

Finding Documents

As Phalcon\Mvc\Collection relies on the Mongo PHP extension you have the same facilities to query documents and convert them transparently to model instances:

<?php

// How many robots are there?
$robots = Robots::find();
echo "There are ", count($robots), "\n";

// How many mechanical robots are there?
$robots = Robots::find(
    array(
        array("type" => "mechanical")
    )
);
echo "There are ", count($robots), "\n";

// Get and print mechanical robots ordered by name upward
$robots = Robots::find(
    array(
        array("type" => "mechanical"),
        "sort" => array("name" => 1)
    )
);

foreach ($robots as $robot)
{
    echo $robot->name, "\n";
}

// Get first 100 mechanical robots ordered by name
$robots = Robots::find(
    array(
        array("type" => "mechanical"),
        "sort" => array("name" => 1),
        "limit" => 100
    )
);

foreach ($robots as $robot)
{
   echo $robot->name, "\n";
}

You could also use the findFirst() method to get only the first record matching the given criteria:

<?php

// What's the first robot in robots collection?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name, "\n";

// What's the first mechanical robot in robots collection?
$robot = Robots::findFirst(
    array(
        array("type" => "mechanical")
    )
);
echo "The first mechanical robot name is ", $robot->name, "\n";

Both find() and findFirst() methods accept an associative array specifying the search criteria:

<?php

// First robot where type = "mechanical" and year = "1999"
$robot = Robots::findFirst(
    array(
        "type" => "mechanical",
        "year" => "1999"
    )
);

// All virtual robots ordered by name downward
$robots = Robots::find(
    array(
        "conditions" => array("type" => "virtual"),
        "sort"       => array("name" => -1)
    )
);

The available query options are:

Parameter Description Example
conditions Search conditions for the find operation. Is used to extract only those records that fulfill a specified criterion. By default Phalcon_model assumes the first parameter are the conditions. “conditions” => array(‘$gt’ => 1990)
sort Is used to sort the resultset. Use one or more fields as each element in the array, 1 means ordering upwards, -1 downward “order” => array(“name” => -1, “statys” => 1)
limit Limit the results of the query to results to certain range “limit” => 10
skip Skips a number of results “skip” => 50

If you have experience with SQL databases, you may want to check the SQL to Mongo Mapping Chart.

Creating Updating/Records

The method Phalcon\Mvc\Collection::save() allows you to create/update documents according to whether they already exist in the collection associated with a model. The save method is called internally by the create and update methods of Phalcon\Mvc\Collection.

Also the method executes associated validators and events that are defined in the model:

<?php

$robot       = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
if ($robot->save() == false)
{
    echo "Umh, We can't store robots right now: \n";
    foreach ($robot->getMessages() as $message)
    {
        echo $message, "\n";
    }
}
else
{
    echo "Great, a new robot was saved successfully!";
}

The “_id” property is automatically updated with the MongoId object created by the driver:

<?php

$robot->save();
echo "The generated id is: ", $robot->getId();
Validation Messages

Phalcon\Mvc\Collection has a messaging subsystem that provides a flexible way to output or store the validation messages generated during the insert/update processes.

Each message consists of an instance of the class Phalcon\Mvc\Model\Message. The set of messages generated can be retrieved with the method getMessages(). Each message provides extended information like the field name that generated the message or the message type:

<?php

if ($robot->save() == false)
{
    foreach ($robot->getMessages() as $message)
    {
        echo "Message: ", $message->getMessage();
        echo "Field: ", $message->getField();
        echo "Type: ", $message->getType();
    }
}
Validation Events and Events Manager

Models allow you to implement events that will be thrown when performing an insert or update. They help to define business rules for a certain model. The following are the events supported by Phalcon\Mvc\Collection and their order of execution:

Operation Name Can stop operation? Explanation
Inserting/Updating beforeValidation YES Is executed before the validation process and the final insert/update to the database
Inserting beforeValidationOnCreate YES Is executed before the validation process only when an insertion operation is being made
Updating beforeValidationOnUpdate YES Is executed before the fields are validated for not nulls or foreign keys when an updating operation is being made
Inserting/Updating onValidationFails YES (already stopped) Is executed before the validation process only when an insertion operation is being made
Inserting afterValidationOnCreate YES Is executed after the validation process when an insertion operation is being made
Updating afterValidationOnUpdate YES Is executed after the validation process when an updating operation is being made
Inserting/Updating afterValidation YES Is executed after the validation process
Inserting/Updating beforeSave YES Runs before the required operation over the database system
Updating beforeUpdate YES Runs before the required operation over the database system only when an updating operation is being made
Inserting beforeCreate YES Runs before the required operation over the database system only when an inserting operation is being made
Updating afterUpdate NO Runs after the required operation over the database system only when an updating operation is being made
Inserting afterCreate NO Runs after the required operation over the database system only when an inserting operation is being made
Inserting/Updating afterSave NO Runs after the required operation over the database system

To make a model to react to an event, we must to implement a method with the same name of the event:

<?php

class Robots extends \Phalcon\Mvc\Collection
{

    public function beforeValidationOnCreate()
    {
        echo "This is executed before create a Robot!";
    }

}

Events can be useful to assign values before perform a operation, for example:

<?php

class Products extends \Phalcon\Mvc\Collection
{

    public function beforeCreate()
    {
        // Set the creation date
        $this->created_at = date('Y-m-d H:i:s');
    }

    public function beforeUpdate()
    {
        // Set the modification date
        $this->modified_in = date('Y-m-d H:i:s');
    }

}

Additionally, this component is integrated with Phalcon\Events\Manager, this means we can create listeners that run when an event is triggered.

<?php

$eventsManager = new Phalcon\Events\Manager();

//Attach an anonymous function as a listener for "model" events
$eventsManager->attach(
    'model',
    function($event, $robot)
    {
        if ($event->getType() == 'beforeSave')
        {
            if ($robot->name == 'Scooby Doo')
            {
                echo "Scooby Doo isn't a robot!";
                return false;
            }
        }
        return true;
    }
);

$robot = new Robots();
$robot->setEventsManager($eventsManager);
$robot->name = 'Scooby Doo';
$robot->year = 1969;
$robot->save();

In the above example the EventsManager only acted as a bridge between an object and a listener (the anonymous function). If we want all objects created in our application use the same EventsManager then we need to assign this to the Models Manager:

<?php

//Registering the collectionManager service
$di->set(
    'collectionManager',
    function()
    {
        $eventsManager = new Phalcon\Events\Manager();

        // Attach an anonymous function as a listener for "model" events
        $eventsManager->attach(
            'model',
            function($event, $model)
            {
                if (get_class($model) == 'Robots')
                {
                    if ($event->getType() == 'beforeSave')
                    {
                        if ($model->name == 'Scooby Doo')
                        {
                            echo "Scooby Doo isn't a robot!";
                            return false;
                        }
                    }
                }
                return true;
            }
        );

        // Setting a default EventsManager
        $modelsManager = new Phalcon\Mvc\Collection\Manager();
        $modelsManager->setEventsManager($eventsManager);
        return $modelsManager;
    }
);
Implementing a Business Rule

When an insert, update or delete is executed, the model verifies if there are any methods with the names of the events listed in the table above.

We recommend that validation methods are declared protected to prevent that business logic implementation from being exposed publicly.

The following example implements an event that validates the year cannot be smaller than 0 on update or insert:

<?php

class Robots extends \Phalcon\Mvc\Collection
{

    public function beforeSave()
    {
        if ($this->year < 0)
        {
            echo "Year cannot be smaller than zero!";
            return false;
        }
    }

}

Some events return false as an indication to stop the current operation. If an event doesn’t return anything, Phalcon\Mvc\Collection will assume a true value.

Validating Data Integrity

Phalcon\Mvc\Collection provides several events to validate data and implement business rules. The special “validation” event allows us to call built-in validators over the record. Phalcon exposes a few built-in validators that can be used at this stage of validation.

The following example shows how to use it:

<?php

use Phalcon\Mvc\Model\Validator\InclusionIn;
use Phalcon\Mvc\Model\Validator\Uniqueness;

class Robots extends \Phalcon\Mvc\Collection
{

    public function validation()
    {

        $this->validate(new InclusionIn(
            array(
                "field"  => "type",
                "domain" => array("Mechanical", "Virtual")
            )
        ));

        $this->validate(new Uniqueness(
            array(
                "field"   => "name",
                "message" => "The robot name must be unique"
            )
        ));

        return $this->validationHasFailed() != true;
    }

}

The above example performs a validation using the built-in validator “InclusionIn”. It checks the value of the field “type” in a domain list. If the value is not included in the method then the validator will fail and return false. The following built-in validators are available:

Name Explanation Example
Email Validates that field contains a valid email format Example
ExclusionIn Validates that a value is not within a list of possible values Example
InclusionIn Validates that a value is within a list of possible values Example
Numericality Validates that a field has a numeric format Example
Regex Validates that the value of a field matches a regular expression Example
Uniqueness Validates that a field or a combination of a set of fields are not present more than once in the existing records of the related table Example
StringLength Validates the length of a string Example

In addition to the built-in validatiors, you can create your own validators:

<?php

class UrlValidator extends \Phalcon\Mvc\Collection\Validator
{

    public function validate($model)
    {
        $field = $this->getOption('field');

        $value    = $model->$field;
        $filtered = filter_var($value, FILTER_VALIDATE_URL);
        if (!$filtered)
        {
            $this->appendMessage("The URL is invalid", $field, "UrlValidator");
            return false;
        }
        return true;
    }

}

Adding the validator to a model:

<?php

class Customers extends \Phalcon\Mvc\Collection
{

    public function validation()
    {
        $this->validate(new UrlValidator(
            array(
                "field"  => "url",
            )
        ));
        if ($this->validationHasFailed() == true)
        {
            return false;
        }
    }

}

The idea of ​​creating validators is make them reusable between several models. A validator can also be as simple as:

<?php

class Robots extends \Phalcon\Mvc\Collection
{

    public function validation()
    {
        if ($this->type == "Old")
        {
            $message = new Phalcon\Mvc\Model\Message(
                "Sorry, old robots are not allowed anymore",
                "type",
                "MyType"
            );
            $this->appendMessage($message);
            return false;
        }
        return true;
    }

}

Deleting Records

The method Phalcon\Mvc\Collection::delete() allows to delete a document. You can use it as follows:

<?php

$robot = Robots::findFirst();
if ($robot != false)
{
    if ($robot->delete() == false)
    {
        echo "Sorry, we can't delete the robot right now: \n";
        foreach ($robot->getMessages() as $message)
        {
            echo $message, "\n";
        }
    }
    else
    {
        echo "The robot was deleted successfully!";
    }
}

You can also delete many documents by traversing a resultset with a foreach:

<?php

$robots = Robots::find(
    array(
        array("type" => "mechanical"
    )
);
foreach ($robots as $robot)
{
    if ($robot->delete() == false)
    {
        echo "Sorry, we can't delete the robot right now: \n";
        foreach ($robot->getMessages() as $message)
        {
            echo $message, "\n";
        }
    }
    else
    {
        echo "The robot was deleted successfully!";
    }
}

The following events are available to define custom business rules that can be executed when a delete operation is performed:

Operation Name Can stop operation? Explanation
Deleting beforeDelete YES Runs before the delete operation is made
Deleting afterDelete NO Runs after the delete operation was made

Validation Failed Events

Another type of events is available when the data validation process finds any inconsistency:

Operation Name Explanation
Insert or Update notSave Triggered when the insert/update operation fails for any reason
Insert, Delete or Update onValidationFails Triggered when any data manipulation operation fails

Setting multiple databases

In Phalcon, all models can belong to the same database connection or have an individual one. Actually, when Phalcon\Mvc\Collection needs to connect to the database it requests the “mongo” service in the application’s services container. You can overwrite this service setting it in the initialize method:

<?php

// This service returns a mongo database at 192.168.1.100
$di->set(
    'mongo1',
    function()
    {
        $mongo = new Mongo("mongodb://scott:nekhen@192.168.1.100");
        return $mongo->selectDb("management");
    }
);

// This service returns a mongo database at localhost
$di->set(
    'mongo2',
    function()
    {
        $mongo = new Mongo("mongodb://localhost");
        return $mongo->selectDb("invoicing");
    }
);

Then, in the Initialize method, we define the connection service for the model:

<?php

class Robots extends \Phalcon\Mvc\Collection
{
    public function initialize()
    {
        $this->setConnectionService('mongo1');
    }

}

Injecting services into Models

You may be required to access the application services within a model, the following example explains how to do that:

<?php

class Robots extends \Phalcon\Mvc\Collection
{

    public function notSave()
    {
        // Obtain the flash service from the DI container
        $flash = $this->getDI()->getShared('flash');

        // Show validation messages
        foreach($this->getMesages() as $message)
        {
            $flash->error((string) $message);
        }
    }

}

The “notSave” event is triggered whenever a “creating” or “updating” action fails. We’re flashing the validation messages obtaining the “flash” service from the DI container. By doing this, we don’t have to print messages after each save.

使用视图(Using Views)

视图(Views)代表的就是你应用程序的用户界面。视图通常由HTML文件嵌入PHP代码组成,视图提供了为用户请求把数据输出到浏览器的任务。

Phalcon\Mvc\View 负责管理MVC应用程序中的视图层。

本组件支持文件的层次结构,这个层次结构允许常用的layout布局,以及使用控制器命名的文件夹名称,定义了各自相应的视图模板。

Integrating Views with Controllers

Phalcon的视图组件会自动通过执行一个特定的控制器完成它的生命周期。视图组件首先要根据最后的控制器名称找到视图文件目录, 然后通过最后的Action找到视图文件名,然后输出视图内容。举例,如果一个URL请求是 http://127.0.0.1/blog/posts/show/301 , Phalcon会这样解析这个URL:

Server Address 127.0.0.1
Phalcon Directory blog
Controller posts
Action show
Parameter 301

分发器会寻找一个“PostsController”和它的的Action “showAction”。一个简单的控制器文件例子:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function showAction($postId)
    {
        // Pass the $postId parameter to the view
        $this->view->setVar("postId", $postId);
    }

}

setVar方法允许我们创建视图变量,以便我们可以在视图文件中使用它们。上面的演示告诉我们如何把 $postId 这个参数绑定到视图文件上。

Phalcon\Mvc\View 使用PHP本身作为模板引擎,因此我们建议使用.phtml作为扩展名。如果视图目录是 app/views ,视图组件会自动找到以下3个视图文件。

Name File Description
Action View app/views/posts/show.phtml This is the view related to the action. It only will be shown when the “show” action was executed.
Controller Layout app/views/layouts/posts.phtml This is the view related to the controller. It only will be shown for every action executed within the controller “posts”. All the code implemented in the layout will be reused for all the actions in this controller.
Main Layout app/views/index.phtml This is main action it will be shown for every controller or action executed within the application.

你并不必要编写上述提到的所有三个视图文件。 Phalcon\Mvc\View 会通过视图文件的层次自动查找下一层的视图文件。如果所有三个视图文件都存在,他们将做如下处理:

<!-- app/views/posts/show.phtml -->

<h3>This is show view!</h3>

<p>I have received the parameter <?php $postId ?></p>
<!-- app/views/layouts/posts.phtml -->

<h2>This is the "posts" controller layout!</h2>

<?php echo $this->getContent() ?>
<!-- app/views/index.phtml -->
<html>
    <head>
        <title>Example</title>
    </head>
    <body>

        <h1>This is main layout!</h1>

        <?php echo $this->getContent() ?>

    </body>
</html>

请注意视图文件中调用 $this->getContent() 方法的那一行。这个方法的位置决定内容在 Phalcon\Mvc\View 的层次结构中的上一个视图的哪个位置显示。上述示例将输出以下内容:

_images/views-1.png

生成的HTML内容如下:

<!-- app/views/index.phtml -->
<html>
    <head>
        <title>Example</title>
    </head>
    <body>

        <h1>This is main layout!</h1>

        <!-- app/views/layouts/posts.phtml -->

        <h2>This is the "posts" controller layout!</h2>

        <!-- app/views/posts/show.phtml -->

        <h3>This is show view!</h3>

        <p>I have received the parameter 101</p>

    </body>
</html>

使用模板(Using Templates)

Templates也是视图文件的一部分,但他们是可共享的。他们作为控制器的布局文件,你必须把它们放到layouts目录下。

<?php

class PostsController extends \Phalcon\Mvc\Controller
{
    public function initialize()
    {
        $this->view->setTemplateAfter('common');
    }

    public function lastAction()
    {
        $this->flash->notice("These are the latest posts");
    }
}
<!-- app/views/index.phtml -->
<!DOCTYPE html>
<html>
    <head>
        <title>Blog's title</title>
    </head>
    <body>
        <?php echo $this->getContent() ?>
    </body>
</html>
<!-- app/views/layouts/common.phtml -->

<ul class="menu">
    <li><a href="/">Home</a></li>
    <li><a href="/articles">Articles</a></li>
    <li><a href="/contact">Contact us</a></li>
</ul>

<div class="content"><?php echo $this->getContent() ?></div>
<!-- app/views/layouts/posts.phtml -->

<h1>Blog Title</h1>

<?php echo $this->getContent() ?>
<!-- app/views/layouts/posts/last.phtml -->

<article>
    <h2>This is a title</h2>
    <p>This is the post content</p>
</article>

<article>
    <h2>This is another title</h2>
    <p>This is another post content</p>
</article>

最后它们将输出如下的HTML内容:

<!-- app/views/index.phtml -->
<!DOCTYPE html>
<html>
    <head>
        <title>Blog's title</title>
    </head>
    <body>

        <!-- app/views/layouts/common.phtml -->

        <ul class="menu">
            <li><a href="/">Home</a></li>
            <li><a href="/articles">Articles</a></li>
            <li><a href="/contact">Contact us</a></li>
        </ul>

        <div class="content">

            <!-- app/views/layouts/posts.phtml -->

            <h1>Blog Title</h1>

            <!-- app/views/layouts/posts/last.phtml -->

            <article>
                <h2>This is a title</h2>
                <p>This is the post content</p>
            </article>

            <article>
                <h2>This is another title</h2>
                <p>This is another post content</p>
            </article>

        </div>

    </body>
</html>

Using Partials

局部模板文件是另一种打破视图渲染顺序的方式,它更易于管理,且可在应用程序中重复使用。

作为局部文件的方式之一可以把它们看作是子程序,把你的视图代码分成多个组成部分,更容易被理解。例如,你可能会有这样的想法,看起来像这样:

<?php $this->partial("shared/ad_banner") ?>

<h1>Robots</h1>

<p>Check out our specials for robots:</p>
...

<?php $this->partial("shared/footer") ?>

Transfer values from the controller to views

Phalcon\Mvc\View 可以在控制器中使用视图变量($this->view)调用。你可以在控制器的Action中使用该对象的setVar()方法设置变量到视图中。

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function showAction()
    {
        //Pass all the posts to the views
        $this->view->setVar("posts", Posts:find());
    }

}

setView()的第一个参数名称是将要在视图文件中使用的,变量可以是任意类型。从字符串,整型数字,到一个更复杂的结构,如数组,集合等都可以。

<div class="post">
<?php

  foreach ($posts as $post)
  {
    echo "<h1>", $post->title, "</h1>";
  }

?>
</div>

Control Rendering Levels

从以上可以看出,Phalcon\Mvc\View 支持视图层次结构。你可能需要在视图中控制显示的层次,PhalconMvc\View::setRenderLevel() 提供这种功能。

此方法可以从控制器或从上级视图层调用改变渲染过程。

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function findAction()
    {

        // This is an Ajax response so don't generate any kind of view
        $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER);

        //...
    }

    public function showAction($postId)
    {
        // Shows only the view related to the action
        $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_ACTION_VIEW);
    }

}

The available render levels are:

Class Constant Description
LEVEL_NO_RENDER Indicates to avoid generating any kind of presentation.
LEVEL_ACTION_VIEW Generates the presentation to the view associated to the action.
LEVEL_BEFORE_TEMPLATE Generates presentation templates prior to the controller layout.
LEVEL_LAYOUT Generates the presentation to the controller layout.
LEVEL_AFTER_TEMPLATE Generates the presentation to the templates after the controller layout.
LEVEL_MAIN_LAYOUT Generates the presentation to the main layout. File views/index.phtml

Using models in the view layer

应用程序中的模型是可以在视图中直接使用的,因为 Phalcon\Loader 在运行时会自动初始化它们:

<div class="categories">
<?php

foreach (Catergories::find("status = 1") as $category) {
   echo "<span class='category'>", $category->name, "</span>";
}

?>
</div>

虽然你可以在视图中执行模型的各种操作,如insert(),update()等,但不建议这么使用。因为它不可以在发生错误或异常的时候从一个控制流程跳转到另一个控制器。

Picking Views

正如上面提示的,Phalcon\Mvc\Application 管理 Phalcon\Mvc\View 进行视图显示,根据相关联的最一个控制器和action来进行视图文件输出。你也可以通过 Phalcon\Mvc\View::pick() 方法改变这个显示流程:

<?php

class ProductsController extends \Phalcon\Mvc\Controller
{

    public function listAction()
    {
        // Pick "views-dir/products/search" as view to render
        $this->view->pick("products/search");
    }

}

Caching View Fragments

有时候,当你开发动态网站时,网页上的有一些区域是不经常更新的,他们每次都输出相同的内容。Phalcon\Mvc\View 提供了一种缓存功能,可以局部缓存,也可以缓存整个页面,以提高性能。

Phalcon\Mvc\View 集成了 Phalcon\Cache ,提供了一种更方便的方法来进行缓存操作。你可以手工设置缓存处理,或设置一个全局的缓存规则:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function showAction()
    {
        //Cache the view using the default settings
        $this->view->cache(true);
    }

    public function showArticleAction()
    {
        // Cache this view for 1 hour
        $this->view->cache(array(
            "lifetime" => 3600
        ));
    }

    public function resumeAction()
    {
        //Cache this view for 1 day with the key "resume-cache"
        $this->view->cache(
            array(
                "lifetime" => 86400,
                "key"      => "resume-cache",
            )
        );
    }

    public function downloadAction()
    {
        //Passing a custom service
        $this->view->cache(
            array(
                "service"  => "myCache",
                "lifetime" => 86400,
                "key"      => "resume-cache",
            )
        );
    }

}

当我们没有为缓存定义一个明确的KEY时,组件会自动创建一个针对视图文件名称 md5 的KEY。这样定义KEY的方式是非常不错的做法,因为这样你就可以很容易识别到每个Action与视图缓存的对应文件了。

当View组件需要缓存一些内容的时候,它将从服务容器请求cache服务。 这个服务在服务容器中的命名为”viewCache”:

<?php

//Set the views cache service
$di->set('viewCache', function(){

    //Cache data for one day by default
    $frontCache = new Phalcon\Cache\Frontend\Output(array(
        "lifetime" => 86400
    ));

    //Memcached connection settings
    $cache = new Phalcon\Cache\Backend\Memcached($frontCache, array(
        "host" => "localhost",
        "port" => "11211"
    ));

    return $cache;
}, true);

当使用视图后,如果有缓存,应直接输出缓存内存进行显示,而不要使控制器再次执行获取数据。

为了实现这一目标,我们必须使用唯一的缓存KEY。首先,我们要先验证缓存的KEY是否存在或是否已过期,整个过程如下:

<?php

class DownloadController extends Phalcon\Mvc\Controller
{

    public function indexAction()
    {

        //Check if the cache with key "downloads" exists or has expired
        if ($this->view->getCache()->exists('downloads')) {

            //Query the latest downloads
            $latest = Downloads::find(array('order' => 'created_at DESC'));

            $this->view->setVar('latest', $latest);
        }

        //Enable the cache with the same key "downloads"
        $this->view->cache(array('key' => 'downloads'));
    }

}

禁用视图(Disabling the view)

如果您的控制器不产生任何输出,您可以禁用视图组件,避免不必要的处理:

<?php

class UsersController extends \Phalcon\Mvc\Controller
{

    public function closeSessionAction()
    {

        //Disable the view
        $this->view->disable();

        //The same
        $this->view->setRenderLevel(Phalcon\Mvc\View::LEVEL_NO_RENDER);
    }

}

模板引擎(Template Engines)

模板引擎可帮助前端设计人员无需使用复杂的语法就可以创建视图。Phalcon自身包含了一个强大快速的模板引擎 Volt

此外, Phalcon\Mvc\View 还允许你使用其他的模板引擎替代PHP或Volt.

使用不同的模板引擎,通常需要复杂的外部PHP库,用于解析模板文件。这通常会增加你的应用程序的资源数量。

如果你要使用一个外部模板引擎, Phalcon\Mvc\View 会提供完全相同的视图层次结构,它同样可以在模板中访问API。

该组件使用适配器,这可以帮助外部模板引擎在Phalcon中是统一的,让我们来看看如何整合其他模板引擎的。

创建自己的模板引擎适配器(Creating your own Template Engine Adapter)

有很多的模板引擎,比如常用的Smarty,你可能需要集成或自己创建一个。使用外部模板引擎的第一步就是要为它创建一个适配器。

模板引擎适配器是一个类,它用作 Phalcon\Mvc\View 与模板引擎集成工作的一个桥梁。通常只需要实现 __construct() 和 render() 两个方法。构造方法用于传入 Phalcon\Mvc\View 的实际对象和服务容器(DI).

render()方法接收两个参数,第一个为视图文件的绝对路径,第二个参数是通过 $this->view->setVar() 设置模板变量。

<?php

class MyTemplateAdapter extends \Phalcon\Mvc\View\Engine
{

    /**
     * Adapter constructor
     *
     * @param \Phalcon\Mvc\View $view
     * @param \Phalcon\DI $di
     */
    public function __construct($view, $di)
    {
        //Initiliaze here the adapter
        parent::__construct($view, $di);
    }

    /**
     * Renders a view using the template engine
     *
     * @param string $path
     * @param array $params
     */
    public function render($path, $params)
    {

        // Access view
        $view = $this->_view;

        // Access options
        $options = $this->_options;

        //Render the view
    }

}
更换模板引擎(Changing the Template Engine)

你可以使用以下方式在控制器中替换或添加一个模板引擎:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {
        // Set the engine
        $this->view->registerEngines(
            array(
                ".my-html" => "MyTemplateAdapter"
            )
        );
    }

    public function showAction()
    {
        // Using more than one template engine
        $this->view->registerEngines(
            array(
                ".my-html" => 'MyTemplateAdapter'
                ".phtml" => 'Phalcon\Mvc\View\Engine\Php'
            )
        );
    }

}

你还可以完全替换模板引擎,或同时使用多个模板引擎都是可以的。 Phalcon\Mvc\View::registerEngines() 方法接收一个数组参数。数组的KEY是扩展名,值为模板名。扩展名称不要一样,以区别使用的是哪个模板引擎。

如果使用多个模板引擎,同时设置的扩展名称一样,那么 Phalcon\Mvc\View 将只显示第一个。

如果你想实现在应用程序中每个请求都使用一个或一组模板引擎,你可以注册view服务到服务容器:

<?php

//Setting up the view component
$di->set('view', function() {

    $view = new \Phalcon\Mvc\View();

    $view->setViewsDir('../app/views/');

    $view->registerEngines(
        array(
            ".my-html" => 'MyTemplateAdapter'
        )
    );

    return $view;
});

为了更好的理解如何创建一个模板引擎适配器,让我们集成两个众所周知的模板:Mustache 和 Twig.

Using Mustache

Mustache 是一个logic-less的模板引擎,可用于多平台多语言。PHP的实现版本在这里 this Github repository

你需要在使用模板适配器前手工加载Mustache的库文件。可以使用autoload的方式,也可以使用include包含文件的方式。

<?php

require "path/to/Mustache/Autoloader.php";
Mustache_Autoloader::register();

Mustache的适配器看起来像这样:

<?php

/**
 * Adapter to use Mustache library as templating engine
 */
class My_Mustache_Adapter extends \Phalcon\Mvc\View\Engine
{

    protected $_mustache;

    protected $_params;

    public function __construct(Phalcon\Mvc\View $view, Phalcon\DI $di)
    {
        $this->_mustache = new Mustache_Engine();
        parent::__construct($view, $di);
    }

    public function render($path, $params)
    {
        if (!isset($params['content'])) {
            $params['content'] = $this->_view->getContent();
        }
        $this->_view->setContent($this->_mustache->render(file_get_contents($path), $params));
    }

}

现在,在控制中你需要把模板引擎替换成 Mustache 适配器,如果你的控制器中的所有Action都使用此模板引擎,你可以在initialize()方法中注册它。

<?php

class PostsController extends \Phalcon\Mvc\Controller implements Phalcon\Mvc\View\EngineInterface
{

    public function initialize()
    {

        // Changing PHP engine by Mustache
        $this->view->registerEngines(
            array(".mhtml" => "My_Mustache_Adapter")
        );

    }

    public function showAction()
    {

        $this->view->setVar("showPost", true);
        $this->view->setVar("title", "some title");
        $this->view->setVar("body", "a cool content");

    }

}

相对的模板文件 (views-dir/posts/show.mhtml) 将使用 Mustache 语法进行解析。

{{#showPost}}
    <h1>{{title}}</h1>
    <p>{{body}}</p>
{{/showPost}}

此外,正如上面看到的,你必须在视图文件中调用方法 $this->getContent() 以包含内容。在Moustache中,它是这么使用的:

<div class="some-menu">
    <!-- the menu -->
</div>

<div class="some-main-content">
    {{content}}
</div>
Using Twig

Twig 是最近比较流行的PHP模板引擎。

你在使用模板引擎适配器前同样需要手工加载Twig的库文件,使用autoloader加载可以按如下方式实现:

<?php

require "path/to/Twig/Autoloader.php";
Twig_Autoloader::register();

Twig模板引擎适配器看起来像这样:

<?php

/**
 * Adapter to use Twig library as templating engine
 */
class My_Twig_Adapter extends \Phalcon\Mvc\View\Engine implements Phalcon\Mvc\View\EngineInterface
{

    protected $_twig;

    public function __construct(Phalcon\Mvc\View $view, Phalcon\DI $di)
    {
        $loader = new Twig_Loader_Filesystem($view->getViewsDir());
        $this->_twig = new Twig_Environment($loader);
        parent::__construct($view, $di);
    }

    public function render($path, $params)
    {
        $view = $this->_view;
        if (!isset($params['content'])) {
            $params['content'] = $view->getContent();
        }
        if (!isset($params['view'])) {
            $params['view'] = $view;
        }
        $relativePath = str_replace($view->getViewsDir(), '', $path);
        $this->_view->setContent($this->_twig->render($relativePath, $params));
    }

}

从上面可以看出,你需要替换默认的模板引擎或让它和其他的模板引擎一起工作。

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function initialize()
    {

        // Changing PHP engine by Twig
        $this->view->registerEngines(
            array(".twig" => "Twig")
        );

    }

    public function showAction()
    {

        $this->view->setVar("showPost", true);
        $this->view->setVar("title", "some title");
        $this->view->setVar("body", "a cool content");

    }

}

在这种情况下,相关的视图文件为views-dir/posts/show.twig,这个文件里面写的是包含twig语法的代码。

{{% if showPost %}}
    <h1>{{ title }}</h1>
    <p>{{ body }}</p>
{{% endif %}}

然后需要把内容包含进来,这里使用变量”content”,和Mustache的方式是一样的:

<div class="some-messages">
    {{ content }}
</div>
Using Smarty

Smarty 是另一个PHP模板引擎,它负责应用逻辑和视图的分隔。

你需要在使用适配器之前手工加载库文件,这么做:

<?php

require_once 'Smarty3/Smarty.class.php';

Smarty模板引擎适配器看起来是这个样子的:

<?php

class SmartyEngine extends \Phalcon\Mvc\View\Engine implements Phalcon\Mvc\View\EngineInterface
{

    protected $_smarty;

    protected $_params;

    public function __construct(Phalcon\Mvc\View $view, Phalcon\DI $di)
    {
        $this->_smarty = new Smarty();
        $this->_smarty->template_dir = '.';
        $this->_smarty->compile_dir = SMARTY_DIR . 'templates_c';
        $this->_smarty->config_dir = SMARTY_DIR . 'configs';
        $this->_smarty->cache_dir = SMARTY_DIR . 'cache';
        $this->_smarty->caching = false;
        $this->_smarty->debugging = true;
        parent::__construct($view, $di);
    }

    public function render($path, $params)
    {
        if (!isset($params['content'])) {
            $params['content'] = $this->_view->getContent();
        }
        foreach($params as $key => $value){
            $this->_smarty->assign($key, $value);
        }
        $this->_view->setContent($this->_smarty->fetch($path));
    }

}

在视图中使用服务(Injecting services in View)

每个视图文件中都包含 Phalcon\DI\Injectable 的实例对象,方便的提供了访问服务容器的功能。

下面的例子演示了如何在框架约定下写一个 jQuery ajax request 。视图文件中包含”url”这个服务,你可以直接使用它:

<script type="text/javascript">

$.ajax({
    url: "<?php echo $this->url->get("cities/get") ?>"
})
.done(function() {
    alert("Done!");
});

</script>

Stand-Alone Component

在Phalcon中,一般使用 glue 组件使一些松散的组件连接在一起相互工作,形成一个full-stack框架开发环境,但是你也可以单独使用 Phalcon\Mvc\View

<?php

$view = new \Phalcon\Mvc\View();
$view->setViewsDir("../app/views/");

// Passing variables to the views, these will be created as local variables
$view->setVar("someProducts", $products);
$view->setVar("someFeatureEnabled", true);

//Start the output buffering
$view->start();

//Render all the view hierarchy related to the view products/list.phtml
$view->render("products", "list");

//Finish the output buffering
$view->finish();

echo $view->getContent();

View Events

Phalcon\Mvc\View 可以将事件发送到 EventsManager 。事件通过”view”来触发。一些返回布尔值false的事件可以被停止,支持下列一些事件:

Event Name Triggered Can stop operation?
beforeRender Triggered before start the render process Yes
beforeRenderView Triggered before render an existing view Yes
afterRenderView Triggered after render an existing view No
afterRender Triggered after complete the render process No

下面的示例演示如何将事件监听器绑定到组件:

<?php

$di->set('view', function() {

    //Create an event manager
    $eventsManager = new Phalcon\Events\Manager();

    //Attach a listener for type "view"
    $eventsManager->attach("view", function($event, $view) {
        echo $event->getType(), ' - ', $view->getActiveRenderPath(), PHP_EOL;
    });

    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir("../app/views/");

    //Bind the eventsManager to the view component
    $view->setEventsManager($eventManagers);

    return $view;
});

下面的示例展示了如何创建一个插件,用来clean/repair 在渲染过程中的HTML代码。我们使用 Tidy 来演示:

<?php

class TidyPlugin
{

    public function afterRender($event, $view)
    {

        $tidyConfig = array(
            'clean' => true,
            'output-xhtml' => true,
            'show-body-only' => true,
            'wrap' => 0,
        );

        $tidy = tidy_parse_string($view->getContent(), $tidyConfig, 'UTF8');
        $tidy->cleanRepair();

        $view->setContent((string) $tidy);
    }

}

//Attach the plugin as a listener
$eventsManager->attach("view:afterRender", new TidyPlugin());

视图助手(View Helpers)

编写和维护HTML标记是一项繁琐的任务,因为有许多命名约定及属性需要考虑。Phalcon提供了 Phalcon\Tag 来处理这种复杂性,然后 Phalcon 会把视图助手编写的代码又生成HTML标记,用于正常显示HTML。

此组件同时可用于 HTML+ PHP 的模板文件中,也可以用于 Volt 模板引擎:

本指南不是一个完整的文档,只讲述了视图助手及其参数使用的其中一部分。完整的API参考,请访问:Phalcon\Tag

使用别名

你可以对类进行别名定义以获取更短的名称,在这种情况下,Tag可以代替 Phalcon\Tag

<?php use \Phalcon\Tag as Tag; ?>

Document Type of Content

Phalcon中,使用 Phalcon\Tag::setDoctype() 助手可以设置HTML文档类型,文档类型的定义可能会影响其他 HTML 标签的输出。 例如,如果你设置为XHTML的文档类型,所有标签必须闭合,也就是说开始标签要有相应的结束标签。

Phalcon\Tag 命名空间定义了以下一些文档类型常量:

Constant Document type
HTML32 HTML 3.2
HTML401_STRICT HTML 4.01 Strict
HTML401_TRANSITIONAL HTML 4.01 Transitional
HTML401_FRAMESET HTML 4.01 Frameset
HTML5 HTML 5
XHTML10_STRICT XHTML 1.0 Strict
XHTML10_TRANSITIONAL XHTML 1.0 Transitional
XHTML10_FRAMESET XHTML 1.0 Frameset
XHTML11 XHTML 1.1
XHTML20 XHTML 2.0
XHTML5 XHTML 5

设置文档类型.

<?php \Phalcon\Tag::setDoctype(\Phalcon\Tag::HTML401_STRICT); ?>

获取文档类型.

<?= \Phalcon\Tag::getDoctype() ?>
<html>
<!-- your HTML code -->
</html>

下面是编译后的HTML代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
<!-- your HTML code -->
</html>

创建表单

在Web应用程序中,从表单中获取用户输入是一个应用程序或网站的重要组成部分。下面的示例演示如何使用视图助手创建一个简单的搜索表单:

<?php use \Phalcon\Tag as Tag; ?>

<!-- Sending the form by method POST -->
<?= Tag::form("products/search") ?>
    <label for="q">Search:</label>
    <?= Tag::textField("q") ?>
    <?= Tag::submitButton("Search") ?>
</form>

<!-- Specyfing another method or attributes for the FORM tag -->
<?= Tag::form(array("products/search", "method" => "get")); ?>
    <label for="q">Search:</label>
    <?= Tag::textField("q"); ?>
    <?= Tag::submitButton("Search"); ?>
</form>

上面的助手代码将生成下面的HTML代码:

<form action="/store/products/search/" method="get">
     <label for="q">Search:</label>
     <input type="text" id="q" value="" name="q" />
     <input type="submit" value="Search" />
</endform>

创建表单元素

Phalcon 提供了一系列的助手用于生成表单元素,比如:文本框,按钮等。助手的第一个参数是要生成的表单的名称,当提交表单时,这个名字被当做数据传递。在控制器中,你可以使用 request对象($this->request)的 getPost()和 getQuery()方法,用这个名字得到用户提交的数据。

<?php echo Phalcon\Tag::textField(array(
    "parent_id",
    "value"=> "5"
)) ?>

<?php echo Phalcon\Tag::textArea(array(
    "comment",
    "This is the content of the text-area",
    "cols" => "6",
    "rows" => 20
)) ?>

<?php echo Phalcon\Tag::passwordField("password") ?>

<?php echo Phalcon\Tag::hiddenField(array(
    "parent_id",
    "value"=> "5"
)) ?>

生成选择菜单

生成选择框是容易的,特别是相关的数据已经存储到PHP数组中时。生成选择框可以使用 Phalcon\Tag::select() 和 Phalcon\Tag::selectStatic(). Phalcon\Tag::select() 是专门设计与 Phalcon\Mvc\Model 一起使用,而 Phalcon\Tag::selectStatic() 则是与PHP数组一起使用。

<?php

// Using data from a resultset
echo Phalcon\Tag::select(
    array(
        "productId",
        Products::find("type = 'vegetables'"),
        "using" => array("id", "name")
    )
);

// Using data from an array
echo Phalcon\Tag::selectStatic(
    array(
        "status",
        array(
            "A" => "Active",
            "I" => "Inactive",
        )
    )
);

下面是生成的HTML代码:

<select id="productId" name="productId">
    <option value="101">Tomato</option>
    <option value="102">Lettuce</option>
    <option value="103">Beans</option>
</select>

<select id="status" name="status">
    <option value="A">Active</option>
    <option value="I">Inactive</option>
</select>

有时,为了显示的需要,你想要添加一个空值的option项:

<?php

// Creating a Select Tag with an empty option
echo Phalcon\Tag::select(
    array(
        "productId",
        Products::find("type = 'vegetables'"),
        "using" => array("id", "name")
    ),
    'useEmpty' => true
);
<select id="productId" name="productId">
    <option value="">Choose..</option>
    <option value="101">Tomato</option>
    <option value="102">Lettuce</option>
    <option value="103">Beans</option>
</select>
<?php

// Creating a Select Tag with an empty option with default text
echo Phalcon\Tag::select(
    array(
        "productId",
        Products::find("type = 'vegetables'"),
        "using" => array("id", "name")
    ),
    'useEmpty' => true,
    'emptyText' => 'Please, choose one...',
    'emptyValue' => '@'
);
<select id="productId" name="productId">
    <option value="@">Please, choose one..</option>
    <option value="101">Tomato</option>
    <option value="102">Lettuce</option>
    <option value="103">Beans</option>
</select>

Assigning HTML attributes

所有的助手都接收一个数组,数组的第一个参数作为名称,其他的用于生成额外的HTML属性。

<?php \Phalcon\Tag::textField(
    array(
        "price",
        "size"        => 20,
        "maxlength"   => 30,
        "placeholder" => "Enter a price",
    )
) ?>

会产生下面的HTML代码:

<input type="text" name="price" id="price" size="20" maxlength="30"
    placeholder="Enter a price" />

Setting Helper Values

From Controllers

在视图中对表单元素设置特定值是一个良好的用户体验,你可以在控制器中通过 Phalcon\Tag::setDefaultValue() 设置默认值。

<?php

class ProductsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {
        Phalcon\Tag::setDefaultValue("color", "Blue");
    }

}

在视图文件中,使用 selectStatic 助手提供一些预设值,名称为 “color”:

<?php

echo \Phalcon\Tag::selectStatic(
    array(
        "color",
        array(
            "Yellow" => "Yellow",
            "Blue"   => "Blue",
            "Red"    => "Red"
        )
    )
);

下面是生成的HTML代码,同时值为 “Blue” 的option选项被默认选中:

<select id="color" name="color">
    <option value="Yellow">Yellow</option>
    <option value="Blue" selected="selected">Blue</option>
    <option value="Red">Red</option>
</select>
From the Request

Phalcon\Tag 助手的一个重要的功能是,它能在请求时保持提交的数据。这样,你就可以轻松的显示验证信息,而不会丢失输入的数据。

Specifying values directly

Every form helper supports the parameter “value”. With it you can specify a value for the helper directly. When this parameter is present, any preset value using setDefaultValue() or via request will be ignored.

Changing dynamically the Document Title

Phalcon\Tag 助手还提供了可以在控制器中动态修改标题的功能。下面的例子演示了这一点:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function initialize()
    {
        Phalcon\Tag::setTitle(" Your Website");
    }

    public function indexAction()
    {
        Phalcon\Tag::prependTitle("Index of Posts - ");
    }

}
<html>
    <head>
        <title><?php \Phalcon\Tag::getTitle(); ?></title>
    </head>
    <body>

    </body>
</html>

下面是生成的HTML代码:

<html>
    <head>
        <title>Index of Posts - Your Website</title>
    </head>
      <body>

      </body>
</html>

Static Content Helpers

Phalcon\Tag 助手还提供了生成 script,link, img 这些标签的功能。它能帮助你在你的应用程序中快速的生成静态资源文件。

Images
<?php

// Generate <img src="/your-app/img/hello.gif">
echo \Phalcon\Tag::image("img/hello.gif");

// Generate <img alt="alternative text" src="/your-app/img/hello.gif">
echo \PhalconTag::image(
    array(
       "img/hello.gif",
       "alt" => "alternative text"
    )
);
Stylesheets
<?php

// Generate <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Rosario" type="text/css">
echo \Phalcon\Tag::stylesheetLink("http://fonts.googleapis.com/css?family=Rosario", false);

// Generate <link rel="stylesheet" href="/your-app/css/styles.css" type="text/css">
echo \Phalcon\Tag::stylesheetLink("css/styles.css");
Javascript
<?php

// Generate <script src="http://localhost/javascript/jquery.min.js" type="text/javascript"></script>
echo \Phalcon\Tag::javascriptInclude("http://localhost/javascript/jquery.min.js", false);

// Generate <script src="/your-app/javascript/jquery.min.js" type="text/javascript"></script>
echo \Phalcon\Tag::javascriptInclude("javascript/jquery.min.js");

创建自定义助手

你可以通过继承 Phalcon\Tag 创建你自己的自定义助手,下面是一个简单的例子:

<?php

class MyTags extends \Phalcon\Tag
{

    /**
    * Generates a widget to show a HTML5 audio tag
    *
    * @param array
    * @return string
    */
    static function audioField($parameters)
    {

        // Converting parameters to array if it is not
        if (!is_array($parameters)) {
            $parameters = array($parameters);
        }

        // Determining attributes "id" and "name"
        if (!isset($parameters[0])) {
            $parameters[0] = $parameters["id"];
        }

        $id = $parameters[0];
        if (!isset($parameters["name"])) {
            $parameters["name"] = $id;
        } else {
            if (!$parameters["name"]) {
                $parameters["name"] = $id;
            }
        }

        // Determining widget value,
        // \Phalcon\Tag::setDefault() allows to set the widget value
        if (isset($parameters["value"])) {
            $value = $parameters["value"];
            unset($parameters["value"]);
        } else {
            $value = self::getValue($id);
        }

        // Generate the tag code
        $code = '<audio id="'.$id.'" value="'.$value.'" ';
        foreach ($parameters as $key => $attributeValue) {
            if (!is_integer($key)) {
                $code.= $key.'="'.$attributeValue.'" ';
            }
        }
        $code.=" />";

        return $code;
    }

}

在下一章中,我们将讨论 Volt ,一个更快的PHP模板引擎,在那里你可以使用由 PhalconTag 提供的一种更友好的语法来使用助手工具。

Volt模板引擎

Volt是一个超快速和设计者友好的模板语言,C语言编写的PHP。它为您提供了一套 助理写一个简单的方法的意见。伏法尔康与其他组件的高度集成, 就像你可以使用它作为一个独立的组件在你的应用程序中。

Volt是一种用C语言编写的超快速并且设计友好的PHP模板引擎,它为你提供了一套很方便的视图助手。Volt与其他的组件高度集成,就像你可以在应用程序中单独使用它一样。

_images/volt.jpg

Volt的灵感来源于 Twig 。最初由Armin Ronacher创建,而它则是受 Jinja 的启发。 因此,许多已经在使用Twig的开发人员将熟练的使用相同的语法。Volt的语法和功能更为强大,更多的元素以及更强的性能。

Volt被编译成PHP代码,因此基本上省却了手动编写PHP代码,实现了业务逻辑与视图分离:

{# app/views/products/show.volt #}

{% block last_products %}

{% for product in products %}
    * Name: {{ product.name|e }}
    {% if product.status == "Active" %}
       Price: {{ product.price + product.taxes/100 }}
    {% endif  %}
{% endfor  %}

{% endblock %}

激活 Volt

作为一种模板引擎,你需要把Volt注册到视图组件,并设置一个扩展名称或者使用默认的扩展名 .phtml :

<?php

//Registering Volt as template engine
$di->set('view', function() {

    $view = new \Phalcon\Mvc\View();

    $view->setViewsDir('../app/views/');

    $view->registerEngines(array(
        ".volt" => 'Phalcon\Mvc\View\Engine\Volt'
    ));

    return $view;
});

使用默认的 ”.phtml” 作为扩展名称:

<?php

$view->registerEngines(array(
    ".phtml" => 'Phalcon\Mvc\View\Engine\Volt'
));

基本使用方法

Volt的代码是由PHP和HTML构成。Volt中有一组特殊的分隔符,{% ... %} 用来执行循环语句或条件判断等,赋值语句使用 {{ ... }}。

下面是一个小示例,用于说明一些基本的功能:

{# app/views/posts/show.phtml #}
<!DOCTYPE html>
<html>
    <head>
        <title>{{ title }} - A example blog</title>
    </head>
    <body>

        {% if show_navigation %}
            <ul id="navigation">
            {% for item in menu %}
                <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
            {% endfor %}
            </ul>
        {% endif %}

        <h1>{{ post.title }}</h1>

        <div class="content">
            {{ post.content }}
        </div>

    </body>
</html>

你可以使用 Phalcon\Mvc\View::setVar 把控制器中的变量传递到视图中。在前面的例子中,有三个变量传递到视图中:title, menu 和 post :

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function showAction()
    {

        $post = Post::findFirst();

        $this->view->setVar("title", $post->title);
        $this->view->setVar("post", $post);
        $this->view->setVar("menu", Menu::find());
        $this->view->setVar("show_navigation", true);

    }

}

变量

变量可以有属性,可以通过使用语法访问他们,如:foo.bar。如果它们是数组,你可以使用 foo[‘bar’] 的方式访问:

{{ post.title }}
{{ post['title'] }}

过滤器

变量可以使用过滤器格式化或修改,管道操作符 “|” 用于接收过滤器过滤变量:

{{ post.title|e }}
{{ post.content|striptags }}
{{ name|capitalize|trim }}

以下列表是Volt内置的过滤器:

Filter Description
e Applies Phalcon\Escaper->escapeHtml to the value
escape Applies Phalcon\Escaper->escapeHtml to the value
trim Applies the trim PHP function to the value. Removing extra spaces
striptags Applies the striptags PHP function to the value. Removing HTML tags
slashes Applies the slashes PHP function to the value. Escaping values
stripslashes Applies the stripslashes PHP function to the value. Removing escaped quotes
capitalize Capitalizes a string by applying the ucwords PHP function to the value
lowercase Change the case of a string to lowercase
uppercase Change the case of a string to uppercase
length Counts the string length or how many items are in an array or object
nl2br Changes newlines \n by line breaks (<br />). Uses the PHP function nl2br
sort Sorts an array using the PHP function asort
json_encode Converts a value into its JSON representation

注释

在Volt模板中可以使用 {# ... #} 分隔符添加注释,他们内部的所有文字将被忽略:

{# note: this is a comment
    {% set price = 100; %}
#}

List of Control Structures

Volt提供了一组基本的但功能强大的控制结构:

For

Loop over each item in a sequence. The following example shows how to traverse a set of “robots” and print his/her name:

<h1>Robots</h1>
<ul>
{% for robot in robots %}
  <li>{{ robot.name|e }}</li>
{% endfor %}
</ul>

for循环嵌套:

<h1>Robots</h1>
{% for robot in robots %}
  {% for part in robot.parts %}
  Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br/>
  {% endfor %}
{% endfor %}
If

As PHP, a if statement checks if an expression is evaluated as true or false:

<h1>Cyborg Robots</h1>
<ul>
{% for robot in robots %}
  {% if robot.type = "cyborg" %}
  <li>{{ robot.name|e }}</li>
  {% endif %}
{% endfor %}
</ul>

The else clause is also supported:

<h1>Robots</h1>
<ul>
{% for robot in robots %}
  {% if robot.type = "cyborg" %}
  <li>{{ robot.name|e }}</li>
  {% else %}
  <li>{{ robot.name|e }} (not a cyborg)</li>
  {% endif %}
{% endfor %}
</ul>

变量赋值

在模板文件中,可以使用 “set” 设置或改变变量的值:

{% set fruits = ['Apple', 'Banana', 'Orange'] %}
{% set name = robot.name %}

Expressions

Volt对表达式提供了一组基本的支持,包括字符串以及常用的操作:

Filter Description
“this is a string” Text between double quotes or single quotes are handled as strings
100.25 Numbers with a decimal part are handled as doubles/floats
100 Numbers without a decimal part are handled as integers
false Constant “false” is the boolean false value
true Constant “true” is the boolean true value
null Constant “null” is the Null value
Arrays

无论你使用PHP 5.3 或 5.4,你都可以用 “[ ]” 括起来的形式来创建数组:

译者注:如果在PHP文件中想用这种方式创建数组,PHP最低版本应该为PHP 5.4

{# Simple array #}
{{ ['Apple', 'Banana', 'Orange'] }}

{# Other simple array #}
{{ ['Apple', 1, 2.5, false, null] }}

{# Multi-Dimensional array #}
{{ [[1, 2], [3, 4], [5, 6]] }}

{# Hash-style array #}
{{ ['first': 1, 'second': 4/2, 'third': '3'] }}
数学计算(Math)

你可以在模板文件中直接使用以下操作符进行计算:

Operator Description
+ Perform an adding operation. {{ 2+3 }} returns 5
- Perform a substraction operation {{ 2-3 }} returns -1
* Perform a multiplication operation {{ 2*3 }} returns 6
/ Perform a division operation {{ 10/2 }} returns 5
% Calculate the remainder of an integer division {{ 10%3 }} returns 1
比较运算符(Comparisions)

下面是在模板中可用的比较运算符:

Operator Description
== Check whether both operands are equal
!= Check whether both operands aren’t equal
<> Check whether both operands aren’t equal
> Check whether left operand is greater than right operand
< Check whether left operand is less than right operand
<= Check whether left operand is less or equal than right operand
>= Check whether left operand is greater or equal than right operand
=== Check whether both operands are identical
!== Check whether both operands aren’t identical
逻辑运算符(Logic)

Logic operators are useful in the “if” expression evaluation to combine multiple tests:

Operator Description
or Return true if the left or right operand is evaluated as true
and Return true if both left and right operands are evaluated as true
not Negates an expression
( expr ) Parenthesis groups expressions
其他操作符(Other Operators)

Additional operators seen the following operators are available:

Operator Description
~ Concatenates both operands {{ “hello ” ~ “world” }}
| Applies a filter in the right operand to the left {{ “hello”|uppercase }}
.. Creates a range {{ ‘a’..’z’ }} {{ 1..10 }}
is Same as == (equals)
is not Same as != (not equals)

The following example shows how to use operators:

{% set robots = ['Voltron', 'Astro Boy', 'Terminator', 'C3PO'] %}

{% for index in 0..robots|length %}
    {% if isset robots[index] %}
        {{ "Name: " ~ robots[index] }}
    {% endif %}
{% endfor %}

Using Tag Helpers

Volt 高度集成 Phalcon\Tag,因此你可以在Volt模板中方便的使用它们:

{{ javascript_include("js/jquery.js") }}

{{ form('products/save', 'method': 'post') }}

    <label>Name</label>
    {{ text_field("name", "size": 32) }}

    <label>Type</label>
    {{ select("type", productTypes, 'using': ['id', 'name']) }}

    {{ submit_button('Send') }}

</form>

下面是生成的PHP代码:

<?php echo Phalcon\Tag::javascriptInclude("js/jquery.js") ?>

<?php echo Phalcon\Tag::form(array('products/save', 'method' => 'post')); ?>

    <label>Name</label>
    <?php echo Phalcon\Tag::textField(array('name', 'size' => 32)); ?>

    <label>Type</label>
    <?php echo Phalcon\Tag::select(array('type', $productTypes, 'using' => array('id', 'name'))); ?>

    <?php echo Phalcon\Tag::submitButton('Send'); ?>

</form>

要想在Volt模板中调用 PhalconTag 助手,你只需要使用它们在Volt中对应的缩写版本即可:

Method Volt function
Phalcon\Tag::linkTo link_to
Phalcon\Tag::textField text_field
Phalcon\Tag::passwordField password_field
Phalcon\Tag::hiddenField hidden_field
Phalcon\Tag::fileField file_field
Phalcon\Tag::checkField check_field
Phalcon\Tag::radioField radio_field
Phalcon\Tag::submitButton submit_button
Phalcon\Tag::selectStatic select_static
Phalcon\Tag::select select
Phalcon\Tag::textArea text_area
Phalcon\Tag::form form
Phalcon\Tag::endForm end_form
Phalcon\Tag::getTitle get_title
Phalcon\Tag::stylesheetLink stylesheet_link
Phalcon\Tag::javascriptInclude javascript_include
Phalcon\Tag::image image
Phalcon\Tag::friendlyTitle friendly_title

视图集成(View Integration)

Volt 模板集成了 Phalcon\Mvc\View, 你的模板层次结构和默认的层次结构一样,你可以这样使用 partials :

{{ content() }}

{{ partial("partials/footer.volt") }}

模板继承(Template Inheritance)

模板继承:你可以创建一个基础模板,其他模板继承自这个基础模板,可提高模板文件的复用性。基础模板使用 blocks 定义一个块,这个块可以是可以被子模板覆盖的。现在让我们假设,我们有以下的基础模板:

{# templates/base.volt #}
<!DOCTYPE html>
<html>
    <head>
        {% block head %}
            <link rel="stylesheet" href="style.css" />
        {% endblock %}
        <title>{% block title %}{% endblock %} - My Webpage</title>
    </head>
    <body>
        <div id="content">{% block content %}{% endblock %}</div>
        <div id="footer">
            {% block footer %}&copy; Copyright 2012, All rights reserved.{% endblock %}
        </div>
    </body>
</html>

其他的模板可以继承自这个基础模板,同时替换掉基础模板中的 block:

{% extends "templates/base.volt" %}

{% block title %}Index{% endblock %}

{% block head %}<style type="text/css">.important { color: #336699; }</style>{% endblock %}

{% block content %}
    <h1>Index</h1>
    <p class="important">Welcome on my awesome homepage.</p>
{% endblock %}

并非所有的 block 都需要在子模板中进行替换(意思是,你可以替换需要的那一部分)。上面的示例最终输出结果如下:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">.important { color: #336699; }</style>
        <title>Index - My Webpage</title>
    </head>
    <body>
        <div id="content">
            <h1>Index</h1>
            <p class="important">Welcome on my awesome homepage.</p>
        </div>
        <div id="footer">
            &copy; Copyright 2012, All rights reserved.
        </div>
    </body>
</html>

作为一个片断,”extends” 后跟的路径是一个相对于视图存放目录的相对路径(即 app/views).

默认情况下,出于对性能的考虑,Volt只检查子模板是否有修改。因为建议在开发阶段初始时使用 ‘compileAlways’ => true。这样的话,模板始终检查父模板是否有修改。

Setting up the Volt Engine

Volt是可以通过配置改变默认的行为的,下面的例子说明如何做到这一点:

<?php

//Register Volt as a service
$di->set('voltService', function($view, $di) {

    $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);

    $volt->setOptions(array(
        "compiledPath" => "../app/compiled-templates/",
        "compiledExtension" => ".compiled"
    ));

    return $volt;
});

//Register Volt as template engine
$di->set('view', function() {

    $view = new \Phalcon\Mvc\View();

    $view->setViewsDir('../app/views/');

    $view->registerEngines(array(
        ".volt" => 'voltService'
    ));

    return $view;
});

如果你不重用 Volt,你可以不把它作为一个服务,而是在注册 view 服务的时候,用匿名函数的方式注册Volt模板引擎:

<?php

//Register Volt as template engine with an anonymous function
$di->set('view', function() {

    $view = new \Phalcon\Mvc\View();

    $view->setViewsDir('../app/views/');

    $view->registerEngines(array(
        ".volt" => function($view, $di) {
            $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);

            //set some options here

            return $volt;
        }
    ));

    return $view;
});

Volt 配置选项:

Option Description Default
compiledPath A writable path where the compiled PHP templates will be placed ./
compiledExtension An additional extension appended to the compiled PHP file .php
compiledSeparator Volt replaces the directory separators / and \ by this separator in order to create a single file in the compiled directory %%
stat Whether Phalcon must check if exists differences between the template file and its compiled path true
compileAlways Tell Volt if the templates must be compiled in each request or only when they change false

相关资源

  • A bundle for Sublime/Textmate is available here
  • Our website is running using Volt as template engine, check out its code on github

MVC Applications

在 Phalcon 中,所有复杂的MVC相关工作都是由 Phalcon\Mvc\Application 来完成的。该组件封装了所有复杂的后台操作,包括每一个组件的实例化,组件之间的集成等。

Single or Multi Module Applications

使用此组件,您可以运行不同类型的MVC结构:

Single Module

单MVC应用程序只包含一个module,可以使用命名空间,但不是必需的。这样的应用程序的文件结构如下:

single/
    app/
        controllers/
        models/
        views/
    public/
        css/
        img/
        js/

如果不使用命名空间,引导文件被用来协调MVC流程:

<?php

$loader = new \Phalcon\Loader();

$loader->registerDirs(
    array(
        '../apps/controllers/',
        '../apps/models/'
    )
)->register();

$di = new \Phalcon\DI\FactoryDefault();

// Registering the view component
$di->set('view', function() {
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir('../apps/views/');
    return $view;
});

try {
    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);
    echo $application->handle()->getContent();
} catch(Phalcon\Exception $e) {
    echo $e->getMessage();
}

如果使用命名空间,引导文件可以这样做:

<?php

$loader = new \Phalcon\Loader();

// Use autoloading with namespaces prefixes
$loader->registerNamespaces(
    array(
        'Single\Controllers' => '../apps/controllers/',
        'Single\Models'      => '../apps/models/',
    )
)->register();

$di = new \Phalcon\DI\FactoryDefault();

// Register the dispatcher setting a Namespace for controllers
// Pay special attention to the double slashes at the end of the
// parameter used in the setDefaultNamespace function
$di->set('dispatcher', function() {
    $dispatcher = new \Phalcon\Mvc\Dispatcher();
    $dispatcher->setDefaultNamespace('Single\Controllers\\');
    return $dispatcher;
});

// Registering the view component
$di->set('view', function() {
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir('../apps/views/');
    return $view;
});

try {
    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);
    echo $application->handle()->getContent();
} catch(Phalcon\Exception $e){
    echo $e->getMessage();
}
Multi Module

一个multi-module(多模块)的应用程序是指使用相同的Document Root,但有超过一个module。在这种情况下,程序的文件结构如下:

multiple/
  apps/
    frontend/
       controllers/
       models/
       views/
       Module.php
    backend/
       controllers/
       models/
       views/
       Module.php
  public/
    css/
    img/
    js/

在 apps/ 目录下的每个目录都有自己的MVC结构,Module.php是每个Module特定的设置:

<?php

namespace Multiple\Backend;

use Phalcon\Mvc\ModuleDefinitionInterface;

class Module implements ModuleDefinitionInterface
{

    /**
     * Register a specific autoloader for the module
     */
    public function registerAutoloaders()
    {

        $loader = new \Phalcon\Loader();

        $loader->registerNamespaces(
            array(
                'Multiple\Backend\Controllers' => '../apps/backend/controllers/',
                'Multiple\Backend\Models'      => '../apps/backend/models/',
            )
        );

        $loader->register();
    }

    /**
     * Register specific services for the module
     */
    public function registerServices($di)
    {

        //Registering a dispatcher
        $di->set('dispatcher', function() {
            $dispatcher = new \Phalcon\Mvc\Dispatcher();
            $dispatcher->setDefaultNamespace("Multiple\Backend\Controllers\\");
            return $dispatcher;
        });

        //Registering the view component
        $di->set('view', function() {
            $view = new \Phalcon\Mvc\View();
            $view->setViewsDir('../apps/backend/views/');
            return $view;
        });
    }

}

一个特殊的引导文件,用以载入 multi-module MVC 结构:

<?php

$di = new \Phalcon\DI\FactoryDefault();

//Specify routes for modules
$di->set('router', function () {

    $router = new \Phalcon\Mvc\Router();

    $router->setDefaultModule("frontend");

    $router->add(
        "/login",
        array(
            'module'     => 'backend',
            'controller' => 'login',
            'action'     => 'index',
        )
    );

    $router->add(
        "/admin/products/:action",
        array(
            'module'     => 'backend',
            'controller' => 'products',
            'action'     => 1,
        )
    );

    $router->add(
        "/products/:action",
        array(
            'controller' => 'products',
            'action'     => 1,
        )
    );

    return $router;

});

try {

    //Create an application
    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);

    // Register the installed modules
    $application->registerModules(
        array(
            'frontend' => array(
                'className' => 'Multiple\Frontend\Module',
                'path'      => '../apps/frontend/Module.php',
            ),
            'backend'  => array(
                'className' => 'Multiple\Backend\Module',
                'path'      => '../apps/backend/Module.php',
            )
        )
    );

    //Handle the request
    echo $application->handle()->getContent();

} catch(Phalcon\Exception $e){
    echo $e->getMessage();
}

如果你想把配置文件完全写入到引导文件,你可以使用一个匿名函数的方式来注册 Module :

<?php

//Creating a view component
$view = new \Phalcon\Mvc\View();

// Register the installed modules
$application->registerModules(
    array(
        'frontend' => function($di) use ($view) {
            $di->setShared('view', function() use ($view) {
                $view->setViewsDir('../apps/frontend/views/');
                return $view;
            });
        },
        'backend' => function($di) use ($view) {
            $di->setShared('view', function() use ($view) {
                $view->setViewsDir('../apps/frontend/views/');
                return $view;
            });
        }
    )
);

Phalcon\Mvc\Application Module注册后,每个匹配的route都必须返回一个有效的module。注册的module都有一个相关的类,用于设置module本身提供的功能。每个module类都必须实现 registerAutoloaders() 和 registerServices() 这两个方法,Phalcon\Mvc\Application 将调用它们执行要执行的module。

了解默认行为

如果你一直关注 tutorial 或 使用 Phalcon Devtools 生成过代码,你可能会熟悉以下的引导文件:

<?php

try {

    // Register autoloaders
    //...

    // Register services
    //...

    // Handle the request
    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);
    echo $application->handle()->getContent();

} catch (\Phalcon\Exception $e) {
    echo "PhalconException: ", $e->getMessage();
}

所有控制器工作的核心是 handle()方法被调用:

<?php

echo $application->handle()->getContent();

如果您不希望使用 Phalcon\Mvc\Application ,上面的代码可以修改如下:

<?php

// Request the services from the services container
$router = $di->get('router');
$router->handle();

$view = $di->getShared('view');

$dispatcher = $di->get('dispatcher');

// Pass the proccessed router parameters to the dispatcher
$dispatcher->setControllerName($router->getControllerName());
$dispatcher->setActionName($router->getActionName());
$dispatcher->setParams($router->getParams());

// Start the view
$view->start();

// Dispatch the request
$dispatcher->dispatch();

// Render the related views
$view->render(
    $dispatcher->getControllerName(),
    $dispatcher->getActionName(),
    $dispatcher->getParams()
);

// Finish the view
$view->finish();

$response = $di->get('response');

// Pass the output of the view to the response
$response->setContent($view->getContent());

// Send the request headers
$response->sendHeaders();

// Print the response
echo $response->getContent();

尽管上面的代码显得比使用 Phalcon\Mvc\Application 罗唆,但它提供了一种替代bootstrap文件的方式。根据你的需要,你可能希望完全掌握哪些类应该被实例化,或使用自己的组件来扩展默认的功能。

Application Events

Phalcon\Mvc\Application 能够将事件发送到 EventsManager,事件管理器通过触发 “application”来实现,支持以下的事件:

Event Name Triggered
beforeStartModule Before initialize a module, only when modules are registered
afterStartModule After initialize a module, only when modules are registered
beforeHandleRequest Before execute the dispatch loop
afterHandleRequest After execute the dispatch loop

下面的示例演示如何在此组件上添加监听器:

<?php

$eventsManager = new Phalcon\Events\Manager();

$application->setEventsManager($eventsManager);

$eventsManager->attach(
    "application",
    function($event, $application) {
        // ...
    }
);

路由器(Routing)

router组件允许定义用户请求对应到哪个控制器或Action。router解析 URI 以确定这些信息。路由器有两种模式:MVC模式和匹配模式(match-only)。第一种模式是使用MVC应用程序的理想选择。

Defining Routes

Phalcon\Mvc\Router 提供了一套先进的路由功能。在MVC模式中,你可以自定义路由规则,对应到你需要的 controllers/actions 上。路由的定义如下:

<?php

// Create the router
$router = new \Phalcon\Mvc\Router();

//Define a route
$router->add(
    "/admin/users/my-profile",
    array(
        "controller" => "users",
        "action"     => "profile",
    )
);

//Another route
$router->add(
    "/admin/users/change-password",
    array(
        "controller" => "users",
        "action"     => "changePassword",
    )
);

$router->handle();

add() 方法接收两个参数,第一个参数是一个匹配字符串,第二个参数为一组可选的路径。在这种情况下,URI /admin/users/my-profile, “users”代表控制器,”profile”代表Ation。目前,该路由器不并不执行控制器和Action,只为组件(如: Phalcon\Mvc\Dispatcher) 收集信息,然后由分发器决定是否立即执行。

应用程序可能有很多个不同的路径,如果一个一个的定义路由的话,会非常麻烦。在这种情况下,我们可以使用更灵活的方式创建route:

<?php

// Create the router
$router = new \Phalcon\Mvc\Router();

//Define a route
$router->add(
    "/admin/:controller/a/:action/:params",
    array(
        "controller" => 1,
        "action"     => 2,
        "params"     => 3,
    )
);

在上面的例子中,我们使用通配符来匹配路由。例如,通过访问URL (/admin/users/a/delete/dave/301) ,解析为:

Controller users
Action delete
Parameter dave
Parameter 301

add()方法接收一个模式,可选择使用预定义占位符和正则表达式修饰符。所有的路由模式必须以斜线字符(/)开始。正则表达式语法使用与 PCRE regular expressions 相同的语法。需要注意的是,不必要添加正则表达式分隔符。所有的路由模式是不区分大小写的。

第二个参数定义了如何将匹配部分绑定到controller/action/parameters。匹配部分是占位符或团圆括号中的子模式。另外,在上述的例子中,第一个子模式匹配(:controller),是route中控制器部分,第二个是action,等。

这些占位符使用正则表达式,更易读,更容易为开发人员理解。支持以下占位符:

Placeholder Regular Expression Usage
/:module /([a-zA-Z0-9_-]+) Matches a valid module name with alpha-numeric characters only
/:controller /([a-zA-Z0-9_-]+) Matches a valid controller name with alpha-numeric characters only
/:action /([a-zA-Z0-9_]+) Matches a valid action name with alpha-numeric characters only
/:params (/.*)* Matches a list of optional words separated by slashes
/:namespace /([a-zA-Z0-9_-]+) Matches a single level namespace name
/:int /([0-9]+) Matches an integer parameter

控制器名称采用驼峰书写规则,这意味着,字符 (-) 和 (_)将被移除,同时把下一个字符转化为大写字符。比如,some_controller被转化为SomeController。

Since you can add many routes as you need using add(), the order in which you add the routes indicates their relevance, last routes added have more relevance than first added. Internally, all defined routes are traversed in reverse order until Phalcon\Mvc\Router finds the one that matches the given URI and processes it, while ignoring the rest.

Parameters with Names

The example below demonstrates how to define names to route parameters:

<?php

$router->add(
    "/news/([0-9]{4})/([0-9]{2})/([0-9]{2})/:params",
    array(
            "controller" => "posts",
            "action"     => "show",
            "year"       => 1, // ([0-9]{4})
            "month"      => 2, // ([0-9]{2})
            "day"        => 3, // ([0-9]{2})
            "params"     => 4, // :params
    )
);

在上述的例子中,该路由并没有定义”controller” 和 “action”部分。这两部分被固定值(“posts” 和 “show”)取代。用户并不知道使用的是哪个控制器。在控制器内部,可以通过以下方式访问这些参数:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function showAction()
    {

        // Return "year" parameter
        $year = $this->dispatcher->getParam("year");

        // Return "month" parameter
        $month = $this->dispatcher->getParam("month");

        // Return "day" parameter
        $day = $this->dispatcher->getParam("day");

    }

}

请注意,上述示例中传递的参数是使用dispatcher获取的。此外,也有另一种方法来创建命名参数作为模式的一部分:

<?php

$router->add(
    "/documentation/{chapter}/{name}.{type:[a-z]+}",
    array(
        "controller" => "documentation",
        "action"     => "show"
    )
);

你可以按上面的例子一样的方式获取他们的值:

<?php

class DocumentationController extends \Phalcon\Mvc\Controller
{

    public function showAction()
    {

        // Returns "name" parameter
        $year = $this->dispatcher->getParam("name");

        // Returns "type" parameter
        $year = $this->dispatcher->getParam("type");

    }

}
Short Syntax

如果你不喜欢使用一个数组的形式来定义路由,可以使用另一种语法。下面的示例产生相同的结果:

<?php

// Short form
$router->add("/posts/{year:[0-9]+}/{title:[a-z\-]+}", "Posts::show");

// Array form:
$router->add(
    "/posts/([0-9]+)/([a-z\-]+)",
    array(
       "controller" => "posts",
       "action"     => "show",
       "year"       => 1,
       "title"      => 2,
    )
);
Mixing Array and Short Syntax

Array and short syntax can be mixed to define a route, in this case note that named parameters automatically are added to the route paths according to the position on which they were defined:

<?php

//First position must be skipped because it is used for
//the named parameter 'country'
$router->add('/news/{country:[a-z]{2}}/([a-z+])/([a-z\-+])',
    array(
        'section' => 2, //Positions start with 2
        'article' => 3
    )
);
Routing to Modules

你可以在路由定义中包含module,这适合多个module的应用程序。定义路由也可以使用缺省设置:

<?php

$router = new Phalcon\Mvc\Router(false);

$router->add('/:module/:controller/:action/:params', array(
    'module' => 1,
    'controller' => 2,
    'action' => 3,
    'params' => 4
));

在这种情况下,URL部分必须包含module的名称。例如,下面的URL:/admin/users/edit/sonny,将被解析为:

Module admin
Controller users
Action edit
Parameter sonny

或者,你也可以绑定特定的module到路由上:

<?php

$router->add("/login", array(
    'module' => 'backend',
    'controller' => 'login',
    'action' => 'index',
));

$router->add("/products/:action", array(
    'module' => 'frontend',
    'controller' => 'products',
    'action' => 1,
));

也可绑定到特定的命名空间上:

<?php

$router->add("/:namespace/login", array(
    'namespace' => 1,
    'controller' => 'login',
    'action' => 'index'
));

controller也可指定全称:

<?php

$router->add("/login", array(
    'controller' => 'Backend\Controllers\Login',
    'action' => 'index'
));
HTTP Method Restrictions

当你使用add()方法添加一个路由时,该路由将应用到所有HTTP方法上。有时候,我们想要限制到一个特定的HTTP方法,比如创建一个RESTful的应用程序时:

<?php

// This route only will be matched if the HTTP method is GET
$router->addGet("/products/edit/{id}", "Posts::edit");

// This route only will be matched if the HTTP method is POST
$router->addPost("/products/save", "Posts::save");

// This route will be matched if the HTTP method is POST or PUT
$router->add("/products/update")->via(array("POST", "PUT"));

Matching Routes

现在,我们需要定义一个路由,以检查定义的路由是否匹配给定的URL。默认情况下,路由的URI可以通过 $_GET[‘url’] 这个变量获得,Phalcon可以使用下列URL重写规则很好的工作:

RewriteEngine On
RewriteCond   %{REQUEST_FILENAME} !-d
RewriteCond   %{REQUEST_FILENAME} !-f
RewriteRule   ^(.*)$ index.php?_url=/$1 [QSA,L]

下面的示例将展示如果使用此组件:

<?php

// Creating a router
$router = new \Phalcon\Mvc\Router();

// Define routes here if any
// ...

// Taking URI from $_GET["_url"]
$router->handle();

// or Setting the URI value directly
$router->handle("/employees/edit/17");

// Getting the processed controller
echo $router->getControllerName();

// Getting the processed action
echo $router->getActionName();

//Get the matched route
$route = $router->getMatchedRoute();

Naming Routes

每个被添加的路由都存储到对象 Phalcon\Mvc\Router\Route 中,这个类封装了路由的细节。例如,我们可以给应用程序中的路由设置一个唯一的名称。如果你想创建URLs,这将非常有用。

<?php

$route = $router->add("/posts/{year}/{title}", "Posts::show");

$route->setName("show-posts");

//or just

$router->add("/posts/{year}/{title}", "Posts::show")->setName("show-posts");

然后,我们可以使用 Phalcon\Mvc\Url 组件通过路由的名称创建一个路由:

<?php

// returns /posts/2012/phalcon-1-0-released
$url->get(array("for" => "show-posts", "year" => "2012", "title" => "phalcon-1-0-released"));

用法示例

下面是自定义路由的例子:

<?php

// matches "/system/admin/a/edit/7001"
$router->add(
    "/system/:controller/a/:action/:params",
    array(
        "controller" => 1,
        "action"     => 2,
        "params"     => 3,
    )
);

// matches "/es/news"
$router->add(
    "/([a-z]{2})/:controller",
    array(
        "controller" => 2,
        "action"     => "index",
        "language"   => 1,
    )
);

// matches "/es/news"
$router->add(
    "/{language:[a-z]{2}}/:controller",
    array(
        "controller" => 2,
        "action"     => "index",
    )
);

// matches "/admin/posts/edit/100"
$router->add(
    "/admin/:controller/:action/:int",
    array(
        "controller" => 1,
        "action"     => 2,
        "id"         => 3,
    )
);

// matches "/posts/2010/02/some-cool-content"
$router->add(
    "/posts/([0-9]{4})/([0-9]{2})/([a-z\-]+)",
    array(
        "controller" => "posts",
        "action"     => "show",
        "year"       => 1,
        "month"      => 2,
        "title"      => 4,
    )
);

// matches "/manual/en/translate.adapter.html"
$router->add(
    "/manual/([a-z]{2})/([a-z\.]+)\.html",
    array(
        "controller" => "manual",
        "action"     => "show",
        "language"   => 1,
        "file"       => 2,
    )
);

// matches /feed/fr/le-robots-hot-news.atom
$router->add(
    "/feed/{lang:[a-z]+}/{blog:[a-z\-]+}\.{type:[a-z\-]+}",
    "Feed::get"
);
请注意,因为控制器和命名空间允许使用正规表达式,因此,一些攻击都可能会反过来推导出文件系统中未经授权的文件。一个安全的正则表达式: /([a-zA-Z0-9_-]+)

Default Behavior

Phalcon\Mvc\Router 有一个默认提供了一个非常简单的路由,总是匹配这样的模式:/:controller/:action/:params 。

例如,对于URL http://phalconphp.com/documentation/show/about.html ,路由将按如下方式解析:

Controller documentation
Action show
Parameter about.html

如果你不想在应用程序中使用路由的默认行为,你可以创建一个路由,并把false参数传递给它:

<?php

// Create the router without default routes
$router = new \Phalcon\Mvc\Router(false);

Setting default paths

你可以对module,controller,action设置默认值,当在路由中找不到路径时,它将自动填充它:

<?php

//Individually
$router->setDefaultController("index");
$router->setDefaultAction("index");

//Using an array
$router->setDefaults(array(
    "controller" => "index",
    "action" => "index"
));

译者注:比如一个单module的站点,URL:http://site/,其中没有controller和action,那么默认它将访问 http://site/index/index

Testing your routes

由于此组件不存在依赖关系,你可以创建一个文件来测试你的路由,如下所示:

<?php

//These routes simulate real URIs
$testRoutes = array(
    '/',
    '/index',
    '/index/index',
    '/index/test',
    '/products',
    '/products/index/',
    '/products/show/101',
);

$router = new Phalcon\Mvc\Router();

//Add here your custom routes

//Testing each route
foreach ($testRoutes as $testRoute) {

    //Handle the route
    $router->handle($testRoute);

    echo 'Testing ', $testRoute, '<br>';

    //Check if some route was matched
    if ($router->wasMatched()) {
        echo 'Controller: ', $router->getControllerName(), '<br>';
        echo 'Action: ', $router->getActionName(), '<br>';
    } else {
        echo 'The route wasn\'t matched by any route<br>';
    }
    echo '<br>';

}

Implementing your own Router

Phalcon 还提供了 Phalcon\Mvc\RouterInterface 接口用来实现自定义路由。

Dispatching Controllers

Phalcon\Mvc\Dispatcher 组件负责在MVC应用程序中负责实例化控制器以及执行所需操作的。了解它的具体运作方法能很好的帮助我们了解整个框架提供的服务。

The Dispatch Loop

很多重要的过程发生在MVC工作流本身,尤其是在控制器部分。这些工作发生在控制调度度期间,控制器文件的读取,加载,初始化,以及操作的执行。如果一个action中的流程跳转到另一个控制器的controller/action上,控制调度器再次启动,为了更好的说明这一点,下面的例子将展示 Phalcon\Mvc\Dispatcher 内部执行的过程:

<?php

//Dispatch loop
while (!$finished) {

    $finished = true;

    $controllerClass = $controllerName."Controller";

    //Instantiating the controller class via autoloaders
    $controller = new $controllerClass();

    // Execute the action
    call_user_func_array(array($controller, $actionName . "Action"), $params);

    // Finished should be reloaded to check if the flow was forwarded to another controller
    // $finished = false;

}

上面的代码没有添加验证器,过滤器以及额外的检查,但它很好的展示了分发器在正常的调度程序中的操作流程。

分发器事件(Dispatch Loop Events)

Phalcon\Mvc\Dispatcher 也能够发送事件到 EventsManager 。事件被触发的类型名称为 “dispatch”。其中的一些事件,返回布尔值false时,可以停止事件的运作。主要支持以下事件:

Event Name Triggered Can stop operation?
beforeDispatchLoop Triggered before enter in the dispatch loop. At this point the dispatcher don’t know if the controller or the actions to be executed exist. The Dispatcher only knows the information passed by the Router. Yes
beforeDispatch Triggered after enter in the dispatch loop. At this point the dispatcher don’t know if the controller or the actions to be executed exist. The Dispatcher only knows the information passed by the Router. Yes
beforeExecuteRoute Triggered before execute the controller/action method. At this point the dispatcher has been initialized the controller and know if the action exist. Yes
afterExecuteRoute Triggered after execute the controller/action method. As operation cannot be stopped, only use this event to make clean up after execute the action No
beforeNotFoundAction Triggered when the action was not found in the controller Yes
beforeException Triggered before the dispatcher throws any exception Yes
afterDispatch Triggered after execute the controller/action method. As operation cannot be stopped, only use this event to make clean up after execute the action Yes
afterDispatchLoop Triggered after exit the dispatch loop No

INVO 教程中演示了如何使用分发器配合 Acl 实现安全认证。

下面的示例将演示如何在分发器上注册监听器事件:

<?php

$di->set('dispatcher', function(){

    //Create an event manager
    $eventsManager = new Phalcon\Events\Manager();

    //Attach a listener for type "dispatch"
    $eventsManager->attach("dispatch", function($event, $dispatcher) {
        //...
    });

    $dispatcher = new \Phalcon\Mvc\Dispatcher();

    //Bind the eventsManager to the view component
    $dispatcher->setEventsManager($eventsManager);

    return $dispatcher;
});

Instantiated controllers act automatically as listeners for dispatch events, so you can implement methods as callbacks:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function beforeExecuteRoute($dispatcher)
    {
        // Executed before every found action
    }

    public function afterExecuteRoute($dispatcher)
    {
        // Executed after every found action
    }

}

Forwarding to other actions

分发器允许我们从一个controller/action跳转到另一个controller/action。这是非常有用的,如果我们需要在代码中进行用户检查等事项,可以将用户重定向到其他页面。

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function saveAction($year, $postTitle)
    {

        // .. store some product and forward the user

        // Forward flow to the index action
        $this->dispatcher->forward(array(
            "controller" => "post",
            "action" => "index"
        ));
    }

}

请记住,”forward”和HTTP重定向不一样,虽然他们显示了相同的结果。”forward”不刷新当前页面,所有的重定向都发生在一个单一的请求中,而HTTP重定向则需要完成两个请求。

更多关于forward的例子:

<?php

// Forward flow to another action in the current controller
$this->dispatcher->forward(array(
    "action" => "search"
));

// Forward flow to another action in the current controller
// passing parameters
$this->dispatcher->forward(array(
    "action" => "search",
    "params" => array(1, 2, 3)
));

// Forward flow to another action in the current controller
// passing parameters
$this->dispatcher->forward(array(
    "action" => "search",
    "params" => array(1, 2, 3)
));

跳转动作按受以下一些参数:

Parameter Triggered
controller A valid controller name to forward to.
action A valid action name to forward to.
params An array of parameters for the action
namespace A valid namespace name where the controller is part of

获取参数(Getting Parameters)

当一条路由提供了命名参数,你可以在控制器,视图文件或者其他任何继承了 Phalcon\DI\Injectable 的组件中获取值。

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function saveAction()
    {

        // Get the post's title passed in the URL as parameter
        $title = $this->dispatcher->getParam("title");

        // Get the post's year passed in the URL as parameter
        // also filtering it
        $year = $this->dispatcher->getParam("year", "int");
    }

}

Handling Not-Found Exceptions

使用 EventsManager ,插入一个挂钩点,以使在controller/action不存在的时候,抛出一个异常信息。

<?php

$di->setShared('dispatcher', function() {

    //Create/Get an EventManager
    $eventsManager = new Phalcon\Events\Manager();

    //Attach a listener
    $eventsManager->attach("dispatch", function($event, $dispatcher, $exception) {

        //The controller exists but the action not
        if ($event->getType() == 'beforeNotFoundAction') {
            $dispatcher->forward(array(
                'controller' => 'index',
                'action' => 'show404'
            ));
            return false;
        }

        //Alternative way, controller or action doesn't exist
        if ($event->getType() == 'beforeException') {
            switch ($exception->getCode()) {
                case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                    $dispatcher->forward(array(
                        'controller' => 'index',
                        'action' => 'show404'
                    ));
                    return false;
            }
        }
    });

    $dispatcher = new Phalcon\Mvc\Dispatcher();

    //Bind the EventsManager to the dispatcher
    $dispatcher->setEventsManager($eventsManager);

    return $dispatcher;
});

实现自定义分发器(Implementing your own Dispatcher)

通过实现 Phalcon\Mvc\DispatcherInterface 接口文件可以在Phalcon中创建一个自定义的分发器。

微应用

With Phalcon you can create “Micro-Framework like” applications. By doing this, you only need to write a minimal amount of code to create a PHP application. Micro applications are suitable to small applications, APIs and prototypes in a practical way.

<?php

$app = new Phalcon\Mvc\Micro();

$app->get('/say/welcome/{name}', function ($name) {
    echo "<h1>Welcome $name!</h1>";
});

$app->handle();

Creating a Micro Application

Phalcon\Mvc\Micro is the class responsible for implementing a micro application.

<?php

$app = new Phalcon\Mvc\Micro();

Defining routes

After instantiating the object, you will need to add some routes. Phalcon\Mvc\Router manages routing internally. Routes must always start with /. A HTTP method constraint to a route can be added, so as to instruct the route to match only the requests matched to the HTTP methods. The following example shows how to define a route for the method GET:

<?php

$app->get('/say/hello/{name}', function ($name) {
    echo "<h1>Hello! $name</h1>";
});

The “get” method indicates that the associated HTTP method is GET. The route /say/hello/{name} also has a parameter {$name} that is passed directly to the route handler. Handlers are executed when a route is matched. A handler could be any callable item in the PHP userland. The following example shows how to defined different types of handlers:

<?php

// With a function
function say_hello($name) {
    echo "<h1>Hello! $name</h1>";
}

$app->get('/say/hello/{name}', "say_hello");

// With a static method
$app->get('/say/hello/{name}', "SomeClass::someSayMethod");

// With a method in an object
$myController = new MyController();
$app->get('/say/hello/{name}', array($myController, "someAction"));

//Anonymous function
$app->get('/say/hello/{name}', function ($name) {
    echo "<h1>Hello! $name</h1>";
});

Phalcon\Mvc\Micro provides a set of methods to define the HTTP method (or methods) which the route is constrained for:

<?php

//Matches if the HTTP method is GET
$app->get('/api/products', "get_products");

//Matches if the HTTP method is POST
$app->post('/api/products/add', "add_product");

//Matches if the HTTP method is PUT
$app->put('/api/products/update/{id}', "update_product");

//Matches if the HTTP method is DELETE
$app->put('/api/products/remove/{id}', "delete_product");

//Matches if the HTTP method is OPTIONS
$app->options('/api/products/info/{id}', "info_product");

//Matches if the HTTP method is GET or POST
$app->map('/repos/store/refs')->via(array('GET', 'POST'));
Routes with Parameters

Defining parameters in routes as very easy as demonstrated above. The parameter name has to be enclosed in brackets. Parameter formatting is also available using regular expressions to ensure consistency of data. This is demonstrated in the example below:

<?php

//This route have two parameters and each of them have a format
$app->get('/posts/{year:[0-9]+}/{title:[a-zA-Z\-]+}', function ($year, $title) {
    echo "<h1>Title: $title</h1>";
    echo "<h2>Year: $year</h2>";
});
Starting Route

Normally, the starting route in an application will be the / route, and it will more frequent than not be accessed by the method GET. This scenario is coded as follows:

<?php

//This is the start route
$app->get('/', function () {
    echo "<h1>Welcome!</h1>";
});
Rewrite Rules

The following rules can be used together with Apache to rewrite the URis:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

Working with Responses

You are free to produce any kind of responses in a handler: directly make an output, use a template engine, include a view, return a json, etc.:

<?php

//Direct output
$app->get('/say/hello', function () {
    echo "<h1>Hello! $name</h1>";
});

//Requiring another file
$app->get('/show/results', function () {
    require 'views/results.php';
});

//Returning a JSON
$app->get('/get/some-json', function () {
    echo json_encode(array("some", "important", "data"));
});

In addition to that, you have access to the service “response”, with which you can manipulate better the response:

<?php

$app->get('/show/data', function () use ($app) {

    //Set the Content-Type header
    $app->response->setContentType('text/plain')->sendHeaders();

    //Print a file
    readfile("data.txt");

});

Making redirections

Redirections could be performed to forward the execution flow to another route:

<?php

//This route makes a redirection to another route
$app->post('/old/welcome', function () use ($app) {
    $app->response->redirect("new/welcome");
});

$app->post('/new/welcome', function () use ($app) {
    echo 'This is the new Welcome';
});

Generating URLs for Routes

Phalcon\Mvc\Url can be used to produce URLs based on the defined routes. You need to set up a name for the route; by this way the “url” service can produce the corresponding URL:

<?php

//Set a route with the name "show-post"
$app->get('/blog/{year}/{title}', function ($year, $title) use ($app) {

    //.. show the post here

})->setName('show-post');

//produce a url somewhere
$app->get('/', function() use ($app){

    echo $app->url->get(array(
        'for' => 'show-post',
        'title' => 'php-is-a-great-framework',
        'year' => 2012
    ));

});

Interacting with the Dependency Injector

In the micro application, a Phalcon\DI\FactoryDefault services container is created implicitly; additionally you can create outside of the application a container to manipulate its services:

<?php

$di = new \Phalcon\DI\FactoryDefault();

$di->set('config', function() {
    return new \Phalcon\Config\Adapter\Ini("config.ini");
});

$app = new Phalcon\Mvc\Micro();

$app->setDI($di);

$app->get('/', function () use ($app) {
    //Read a setting from the config
    echo $app->config->app_name;
});

$app->post('/contact', function () use ($app) {
    $app->flash->success('Yes!, the contact was made!');
});

Not-Found Handler

When a user tries to access a route that is not defined, the micro application will try to execute the “Not-Found” handler. An example of that behavior is below:

<?php

$app->notFound(function () use ($app) {
    $app->response->setStatusCode(404, "Not Found")->sendHeaders();
    echo 'This is crazy, but this page was not found!';
});

Models in Micro Applications

Models can be used transparently in Micro Applications, only is required an autoloader to load models:

<?php

$loader = new \Phalcon\Loader();

$loader->registerDirs(array(
    __DIR__.'/models/'
))->register();

$app = new \Phalcon\Mvc\Micro();

$app->get('/products/find', function(){

    foreach (Products::find() as $product) {
        echo $product->name, '<br>';
    }

});

$app->handle();

Micro Application Events

Phalcon\Mvc\Micro is able to send events to the EventsManager (if it is present). Events are triggered using the type “micro”. The following events are supported:

Event Name Triggered Can stop operation?
beforeHandleRoute The main method is just called, at this point the application don’t know if there is some matched route Yes
beforeExecuteRoute A route has been matched and it contains a valid handler, at this point the handler has not been executed Yes
afterExecuteRoute Triggered after running the handler No
beforeNotFound Triggered when any of the defined routes match the requested URI Yes
afterHandleRoute Triggered after completing the whole process in a successful way Yes

In the following example, we explain how to control the application security using events:

<?php

//Create a events manager
$eventManager = \Phalcon\Events\Manager();

//Listen all the application events
$eventManager->attach('micro', function($event, $app) {

    if ($event->getType() == 'beforeExecuteRoute') {
        if ($app->session->get('auth') == false) {
            $app->flashSession->error("The user isn't authenticated");
            $app->response->redirect("/");
        }
    }

});

$app = new Phalcon\Mvc\Micro();

//Bind the events manager to the app
$app->setEventsManager($eventsManager);

Creating a Simple REST API is a tutorial that explains how to create a micro application to implement a RESTful web service.

使用命名空间

Namespaces 可以用来避免类名冲突,这意味着,如果你有两个控制器,在应用程序中使用相同的名称, 可以使用命名空间来区分他们。命名空间是也可用于创建module。

Setting up the framework

使用命名空间时对加载相应控制器会有一定的影响。需要调整框架命名空间的行为,可以实现加载一个或全部:

使用自动加载的方式需要考虑命名空间的影响,以下是使用 Phalcon\Loader 的示例:

<?php

$loader->registerNamespaces(
    array(
       'Store\Admin\Controllers'    => "../bundles/admin/controllers/",
       'Store\Admin\Models'    => "../bundles/admin/models/",
    )
);

在定义路由时,控制器的路径可以指定控制器的全名称:

<?php

$router->add(
    "/admin/users/my-profile",
    array(
        "controller" => "Store\Admin\Users",
        "action"     => "profile",
    )
);

把命名空间当作路由定义的参数(详见路由器章节):

<?php

$router->add(
    "/:namespace/admin/users/my-profile",
    array(
        "namespace"  => 1,
        "controller" => "Users",
        "action"     => "profile",
    )
);

如果你只在你的应用程序中对每个控制器使用相同的命名空间,那么你可以在注册分发器时定义一个默认的命名空间,这样做的话,你就不再需要在定义路由的时候指定完整的类名称了:

<?php

//Registering a dispatcher
$di->set('dispatcher', function() {
    $dispatcher = new \Phalcon\Mvc\Dispatcher();
    $dispatcher->setDefaultNamespace('Store\Admin\Controllers\\');
    return $dispatcher;
});

Controllers with Namespaces

下面的示例演示如何实现使用命名空间来编写一个控制器:

<?php

namespace Store\Admin\Controllers;

class UsersController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function profileAction()
    {

    }

}

Models in Namespaces

对于模型,使用getSource来指定关联的数据表是非常必要的:

<?php

namespace Store\Toys;

class Robots extends \Phalcon\Mvc\Model
{

    public function getSource()
    {
        return "robots";
    }

}

另外,因为命名空间的原因,一些魔术方法不能如预期般运行,你可以按如下方式手工定义正确的行为:

<?php

namespace Store\Toys;

class Robots extends \Phalcon\Mvc\Model
{

    public function getSource()
    {
        return "robots";
    }

    public function initialize()
    {
        $this->hasMany("id", 'Store\Toys\RobotsParts', 'robots_id');
    }

    public function getRobotsParts($arguments=null)
    {
        return $this->getRelated('Store\Toys\RobotsParts', $arguments);
    }

}

事件管理

此组件的目的是通过创建挂钩点拦截框架中大部分组件的执行。这些挂钩点允许开发者获取状态信息,操作数据或改变一个组件在执行过程中的流程。

译者注:挂钩点(hooks point)类似于SVN或GIT中的hook。在使用SVN开发过程中,我们想实现把提交的代码直接部署到演示环境下,那么就需要SVN的hook.

使用示例

在下面的例子中,我们使用EventsManager侦听使用 Phalcon\Db 进行MySQL连接管理过程中产生的事件。首先,我们需要一个侦听器对象,我们创建一个类,它的方法是我们要侦听的事件:

<?php

class MyDbListener
{

    public function afterConnect()
    {

    }

    public function beforeQuery()
    {

    }

    public function afterQuery()
    {

    }

}

这个新的类文件可以更详细一些,因为我们需要使用它。EventsManager 将充当组件与侦听器之间的桥梁,为我们创建的侦听类的方法提供挂钩点:

<?php

$eventsManager = new \Phalcon\Events\Manager();

//Create a database listener
$dbListener = new MyDbListener()

//Listen all the database events
$eventsManager->attach('db', $dbListener);

$connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
    "host" => "localhost",
    "username" => "root",
    "password" => "secret",
    "dbname" => "invo"
));

//Assign the eventsManager to the db adapter instance
$connection->setEventsManager($eventsManager);

//Send a SQL command to the database server
$connection->query("SELECT * FROM products p WHERE p.status = 1");

为了记录我们的应用程序执行的所有SQL语句,我们需要使用事件“afterQuery”。第一个参数传递给 事件侦听器,包含正在运行的事件的上下文信息,第二个是连接本身。

<?php

class MyDbListener
{

    protected $_logger;

    public function __construct()
    {
        $this->_logger = new \Phalcon\Logger\Adapter\File("../apps/logs/db.log");
    }

    public function afterQuery($event, $connection)
    {
        $this->_logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
    }

}

作为示例的一部分,我们需要实现 Phalcon\Db\Profiler,以检测SQL语句比预期花费多长时间:

<?php

class MyDbListener
{

    protected $_profiler;

    protected $_logger;

    public function __construct()
    {
        $this->_profiler = new \Phalcon\Db\Profiler();
        $this->_logger = new \Phalcon\Logger\Adapter\File("../apps/logs/db.log");
    }

    public function beforeQuery($event, $connection)
    {
        $this->_profiler->startProfile($connection->getSQLStatement());
    }

    public function afterQuery($event, $connection)
    {
        $this->_logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
        $this->_profiler->stopProfile();
    }

    public function getProfiler()
    {
        return $this->_profiler;
    }

}

可以从监听器获得返回的数据:

<?php

//Send a SQL command to the database server
$connection->query("SELECT * FROM products p WHERE p.status = 1");

foreach($dbListener->getProfiler()->getProfiles() as $profile){
    echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
    echo "Start Time: ", $profile->getInitialTime(), "\n"
    echo "Final Time: ", $profile->getFinalTime(), "\n";
    echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";
}

以类似的方式,我们可以注册一个lambda形式的匿名函数来执行任务,而不是一个单独的监听器类(见上面示例):

<?php

//Listen all the database events
$eventManager->attach('db', function($event, $connection) {
    if ($event->getType() == 'afterQuery') {
        echo $connection->getSQLStatement();
    }
});

Creating components that trigger Events

你也可以在应用程序中创建自己的组件,使用EventsManager触发事件。作为结果,事件运行时监听器会作出相应的反应。在下面的例子中,我们创建了一个叫”MyComponent”的组件。这个组件实现了EventsManager aware接口,当它的方法 “someTask” 执行时,监听器会触发相应的两个事件:

<?php

class MyComponent implements \Phalcon\Events\EventsAwareInterface
{

    protected $_eventsManager;

    public function setEventsManager($eventsManager)
    {
        $this->_eventsManager = $eventsManager;
    }

    public function getEventsManager()
    {
        return $this->_eventsManager
    }

    public function someTask()
    {
        $this->_eventsManager->fire("my-component:beforeSomeTask", $this);

        // do some task

        $this->_eventsManager->fire("my-component:afterSomeTask", $this);
    }

}

请注意,这个事件在触发时使用的前辍是 “my-component”,这是一个唯一标志字符,以帮助我们知道事件是由哪个组件产生的。你甚至可以在组件之个创建相同名称的事件。现在,让我们来创建一个监听器监听这个组件:

<?php

class SomeListener
{

    public function beforeSomeTask($event, $myComponent)
    {
        echo "Here, beforeSomeTask\n";
    }

    public function afterSomeTask($event, $myComponent)
    {
        echo "Here, afterSomeTask\n";
    }

}

一个监听器就是一个简单的类文件,它实现了所有组件触发的事件。现在,让我们使他们联合在一起工作:

<?php

//Create an Events Manager
$eventsManager = new Phalcon\Events\Manager();

//Create the MyComponent instance
$myComponent = new MyComponent();

//Bind the eventsManager to the instance
$myComponent->setEventsManager($myComponent);

//Attach the listener to the EventsManager
$eventsManager->attach('my-component', new SomeListener());

//Execute methods in the component
$myComponent->someTask();

“someTask”执行后,监听器中的两个方法也会被执行,下面是输出结果:

Here, beforeSomeTask
Here, afterSomeTask

其他数据也可以通过 “fire” 调用第三个参数进行触发:

<?php

$eventsManager->fire("my-component:afterSomeTask", $this, $extraData);

在监听器中,第三个参数也接收此数据:

<?php

//Receiving the data in the third parameter
$eventManager->attach('my-component', function($event, $component, $data) {
    print_r($data);
});

//Receiving the data from the event context
$eventManager->attach('my-component', function($event, $component) {
    print_r($event->getData());
});

如果监听器只对一个特定类型的事件感兴趣,你可以直接绑定:

<?php

//The handler will only be executed if the event triggered is "beforeSomeTask"
$eventManager->attach('my-component:beforeSomeTask', function($event, $component) {
    //...
});

事件的发布与取消(Event Propagation/Cancelation)

许多监听器可能会添加相同的事件,这意味着,对于同类类型的事件,许多监听器都会被触发(即会有非常多同类型的消息输出)。根据注册到 EventsManager 的顺序,监听器被一一触发。一些事件可以被撤消,表明可以停止一些其他的监听器事件被触发:

<?php

$eventsManager->attach('db', function($event, $connection){

    //We stop the event if it is cancelable
    if ($event->isCancelable()) {
        //Stop the event, so other listeners will not be notified about this
        $event->stop();
    }

    //...

});

在默认情况下,事件是可以被取消的,甚至在框架中的大部分事件都是可以被取消的。你可以使用fire方法传递第四个参数,值为”false”,以达到不可取消的目的:

<?php

$eventsManager->fire("my-component:afterSomeTask", $this, $extraData, false);

实现自定义EventsManager(Implementing your own EventsManager)

The Phalcon\Events\ManagerInterface interface must be implemented to create your own EventsManager replacing the one provided by Phalcon.

Request Environment

每一个HTTP请求(通常是由浏览器发起的)包含额外的信息,如头数据的请求,文件,变量等。 基于Web的应用程序的文件需要分析这些信息,以提供正确的 响应返回给请求者。 Phalcon\HTTP\Request 封装 信息的请求,允许你在一个面向对象的方法来访问它。

<?php

// Getting a request instance
$request = new \Phalcon\Http\Request();

// Check whether the request was made with method POST
if ($request->isPost() == true) {
    // Check whether the request was made with Ajax
    if ($request->isAjax() == true) {
        echo "Request was made using POST and AJAX";
    }
}

获取数据

PHP根据请求的类型自动填充超全局变量$_GET 和 $_POST。这些数组包含表单提交或通过URL请求的参数。这些数组中的变量值是未加过滤的,可能包含非法字符,甚至是恶意代码,这可能会导致 SQL injection or Cross Site Scripting (XSS) 攻击。

Phalcon\HTTP\Request 允许你访问$_REQUEST, $_GET 和 $_POST 这些数组中的值,并且可以通过”filter” (by default Phalcon\Filter) 服务对他们进行过滤或消毒。下面的例子提供与原始PHP获取数据相同的行为:

<?php

// Manually applying the filter
$filter = new Phalcon\Filter();

$email  = $filter->sanitize($_POST["user_email"], "email");

// Manually applying the filter to the value
$filter = new Phalcon\Filter();
$email  = $filter->sanitize($request->getPost("user_email"), "email");

// Automatically applying the filter
$email = $request->getPost("user_email", "email");

// Setting a default value if the param is null
$email = $request->getPost("user_email", "email", "some@example.com");

// Setting a default value if the param is null without filtering
$email = $request->getPost("user_email", null, "some@example.com");

在控制器中使用Request

访问请求最常见的地方发生在controller/action中。要想在控制器中访问 Phalcon\HTTP\Request 对象,你可以使用 $this->request 这个公共属性:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function saveAction()
    {

        // Check if request has made with POST
        if ($this->request->isPost() == true) {

            // Access POST data
            $customerName = $this->request->getPost("name");
            $customerBorn = $this->request->getPost("born");

        }

    }

}

文件上传

另一种常见的任务是文件上传。Phalcon\HTTP\Request 提供了一个面向对象的方式来实现这个任务:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function uploadAction()
    {
        // Check if the user has uploaded files
        if ($this->request->hasFiles() == true) {
            // Print the real file names and sizes
            foreach ($this->request->getUploadedFiles() as $file) {

                //Print file details
                echo $file->getName(), " ", $file->getSize(), "\n";


                //Move the file into the application
                $file->moveTo('files/');
            }
        }
    }

}

Phalcon\Http\Request::getUploadedFiles() 返回的每个对象是类文件 Phalcon\Http\Request\File 的实际对象。使用 $_FILES 超全局变量提供了相同的行为。Phalcon\Http\Request\File 封装了上传请求中的单个文件信息。

Working with Headers

正如上面提到的,请求头非常有用,它使我们能够发送适当的响应返回给用户。下面的例子将向你展示使用的方法:

<?php

// get the Http-X-Requested-With header
$requestedWith = $response->getHeader("X_REQUESTED_WITH");
if ($requestedWith == "XMLHttpRequest") {
    echo "The request was made with Ajax";
}

// Same as above
if ($request->isAjax()) {
    echo "The request was made with Ajax";
}

// Check the request layer
if ($request->isSecureRequest() == true) {
    echo "The request was made using a secure layer";
}

// Get the servers's ip address. ie. 192.168.0.100
$ipAddress = $request->getServerAddress();

// Get the client's ip address ie. 201.245.53.51
$ipAddress = $request->getClientAddress();

// Get the User Agent (HTTP_USER_AGENT)
$userAgent = $request->getUserAgent();

// Get the best acceptable content by the browser. ie text/xml
$contentType = $request->getAcceptableContent();

// Get the best charset accepted by the browser. ie. utf-8
$charset = $request->getBestCharset();

// Get the best language accepted configured in the browser. ie. en-us
$language = $request->getBestLanguage();

Returning Responses

HTTP周期的一部分工作是将用户请求的内容正确返回给用户。Phalcon框架使用组件 Phalcon\HTTP\Response 来实现这个任务。HTTP响应(HTTP responses)通常由头部信息及网页主体组成。下面是基本的使用语法:

<?php

// Getting a request instance
$request = new \Phalcon\Http\Request();

//Set status code
$response->setRawHeader(404, "Not Found");

//Set the content of the response
$response->setContent("Sorry, the page doesn't exist");

//Send response to the client
$response->send();

发送头部信息(Working with Headers)

头部信息(Headers)是整个HTTP响应中的重要组成部分。它包括响应状态,如HTTP状态,响应的类型等非常有用的信息。

你可以通过以下方法设置头部信息:

<?php

//Setting it by its name
$response->setHeader("Content-Type", "application/pdf");
$response->setHeader("Content-Disposition", 'attachment; filename="downloaded.pdf"');

//Setting a raw header
$response->setRawHeader("HTTP/1.1 200 OK");

HTTP头部信息由 Phalcon\HTTP\Response\Headers 管理,这个类允许在向客户端发回数据前,向客户端发送HTTP头部信息:

<?php

//Get the headers bag
$headers = $response->getHeaders();

//Get a header by its name
$contentType = $response->getHeaders()->get("Content-Type");

使用重定向(Making Redirections)

使用 Phalcon\HTTP\Response ,你可以实现HTTP重定向:

<?php

//Making a redirection using the local base uri
$response->redirect("posts/index");

//Making a redirection to an external URL
$response->redirect("http://en.wikipedia.org", true);

//Making a redirection specifyng the HTTP status code
$response->redirect("http://www.example.com/new-location", true, 301);

所有由 “url”服务(by default Phalcon\Mvc\Url)产生的内部连接,你可以在程序中这样使用重定向到其他路由上:

<?php

//Making a redirection based on a named route
$response->redirect(array(
    "for" => "index-lang",
    "lang" => "jp",
    "controller" => "index"
));

需要注意的是,重定向不会禁用视图组件。因此,如果你想从一个controller/action重定向到另一个controller/acton上,视图将正常显示。当然,你也可以使用 $this->view->disable() 禁用视图输出。

Generating URLs and Paths

在Phalcon应用程序中,使用 Phalcon\Mvc\Url 组件生成URL。它能够生成基于路由的独立的URL。

Setting a base URI

根据你的应用程序安装到主机文档目录的位置,你的应用程序URI可能会出现一个基础的URI。

例如,如果你的主机文档目录是 /var/www/htdocs,而你的应用程序安装到 /var/www/htdocs/invo,那么基础URI即为 /invo/.如果你使用虚拟主机的形式安装此应用,那么baseUri即为 /. 执行以下代码,你可以检测你的应用程序的baseUri.

<?php

$url = new Phalcon\Mvc\Url();
echo $url->getBaseUri();

默认情况下,Phalcon 会自动检测应用程序的baseUri.但如果你想提高应用程序性能的话,最好还是手工设置:

<?php

$url = new Phalcon\Mvc\Url();

$url->setBaseUri('/invo/');

通常情况下,此组件必须被注册到服务容器中,因此你可以直接这样设置它:

<?php

$di->set('url', function(){
    $url = new Phalcon\Mvc\Url();
    $url->setBaseUri('/invo/');
    return $url;
});

Generating URIs

如果你使用的是 Router 的默认行为。你的应用程序会匹配路由模式 : /:controller/:action/:params. 因此,很容易通过”get”方法得到:

<?php echo $url->get("products/save") ?>

请注意,预先设置baseUri并不是必须的。如果你已经通过设置路由命名,你可以很容易改变它。例如,你有以下途径:

<?php

$route->add('/blog/{$year}/{month}/{title}', array(
    'controller' => 'posts',
    'action' => 'show'
))->setName('show-post');

生成URL还可以通过以下方式:

<?php

//This produces: /blog/2012/01/some-blog-post
$url->get(array(
    'for' => 'show-post',
    'year' => 2012,
    'month' => '01',
    'title' => 'some-blog-post'
));

Producing URLs without Mod-Rewrite

你还可以使用此组件在不使用重写规则的情况下创建URL:

<?php

$url = new Phalcon\Mvc\Url();

//Pass the URI in $_GET["_url"]
$url->setBaseUri('/invo/index.php?_url=/');

//This produce: /invo/index.php?_url=/products/save
echo $url->get("products/save");

你也可以使用 $_SERVER[“REQUEST_URI”]:

<?php

$url = new Phalcon\Mvc\Url();

//Pass the URI using $_SERVER["REQUEST_URI"]
$url->setBaseUri('/invo/index.php?_url=/');

//Pass the URI in $_GET["_url"]
$url->setBaseUri('/invo/index.php/');

在这种情况下,你必须手工处理路由中的URI:

<?php

$router = new Phalcon\Mvc\Router();

// ... define routes

$uri = str_replace($_SERVER["SCRIPT_NAME"], '', $_SERVER["REQUEST_URI"]);
$router->handle($uri);

产生的路由看起来像这样:

<?php

//This produce: /invo/index.php/products/save
echo $url->get("products/save");

Implementing your own Url Generator

The Phalcon\Mvc\UrlInterface interface must be implemented to create your own URL generator replacing the one providing by Phalcon.

发送消息(Flashing Messages)

发送消息被用于向用户发送请求状态或用户行为等。使用此组件可以生成消息。

适配器(Adapters)

此组件使用适配器来决定使用哪种行为向用户发送消息:

Adapter Description API
Direct Directly outputs the messages passed to the flasher Phalcon\Flash\Direct
Session Temporarily stores the messages in session, then messages can be printed in the next request Phalcon\Flash\Session

使用方法(Usage)

通常情况下,消息发送这个服务被注册到服务容器中,如果你使用 Phalcon\DI\FactoryDefault,那么默认将自动注册 “flash”服务为类型 Phalcon\Flash\Direct

<?php

//Set up the flash service
$di->set('flash', function() {
    return new \Phalcon\Flash\Direct();
});

通过这种方式,你可以直接在控制器或视图文件中访问此服务:

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function saveAction()
    {
        $this->flash->success("The post was correctly saved!");
    }

}

内置支持的消息类型有:

<?php

$this->flash->error("too bad! the form had errors");
$this->flash->success("yes!, everything went very smoothly");
$this->flash->notice("this a very important information");
$this->flash->warning("best check yo self, you're not looking too good.");

你也可以增加你自己的消息类型:

<?php

$this->flash->message("debug", "this is debug message, you don't say");

输出消息

消息发送到客户端会自动转化为HTML:

<div class="errorMessage">too bad! the form had errors</div>
<div class="successMessage">yes!, everything went very smoothly</div>
<div class="noticeMessage">this a very important information</div>
<div class="warningMessage">best check yo self, you're not looking too good.</div>

可以看出,有一些CSS的类名被自动添加到DIV上。这些CSS类允许你自定义在浏览器中的显示形式。CSS类可以被覆盖,例如,如果你使用 Twitter bootstrap,CSS类需这样定义:

<?php

//Register the flash service with custom CSS classes
$di->set('flash', function(){
    $flash = new \Phalcon\Flash\Direct(array(
        'error' => 'alert alert-error',
        'success' => 'alert alert-success',
        'notice' => 'alert alert-info',
    ));
    return $flash;
});

上例将输出以下HTML:

<div class="alert alert-error">too bad! the form had errors</div>
<div class="alert alert-success">yes!, everything went very smoothly</div>
<div class="alert alert-info">this a very important information</div>

适配器选型(Implicit Flush vs. Session)

根据选用的适配器类型,它可以直接输出消息,也可以暂时存储到用户会话中,稍后再显示。应该选用哪种适配器?这通常取决于发送消息在页面重定向之前还是之后。例如,如果你对页面做了一个”forward”类型的重定向,那么就没有必要把消息存储到用户会话中,但是如果你做了一个HTTP重定向,你需要把消息存储到用户会话中:

<?php

class ContactController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function saveAction()
    {

        //store the post

        //Using direct flash
        $this->flash->success("Your information were stored correctly!");

        //Forward to the index action
        return $this->dispatcher->forward(array("action" => "index"));
    }

}

或使用HTTP重定向:

<?php

class ContactController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function saveAction()
    {

        //store the post

        //Using session flash
        $this->flashSession->success("Your information were stored correctly!");

        //Make a full HTTP redirection
        return $this->response->redirect("contact/index");
    }

}

在这种情况下,你需要手工设置消息在相应视图中的显示位置:

<!-- app/views/contact/index.phtml -->

<p><?php $this->flashSession->output() ?></p>

属性 ‘flashSession’ 是之前注册’flash’服务到容器中时产生的。

把数据存储到Session(Storing data in Session)

Phalcon\Session 组件提供了一种面象对象的方式访问session数据。

初始化Session

有一些应用程序是会话密集型的,几乎所有的操作都需要访问Session数据。还有一些则不太需要用户会话。有了服务容器,我们可以确保只有在需要它的时候,就可以访问它:

<?php

//Start the session the first time when some component request the session service
$di->setShared('session', function(){
    $session = new Phalcon\Session\Adapter\Files();
    $session->start();
    return $session;
});

存储/获取 Session数据

你可以在控制器,视图文件,以及只要继承自 Phalcon\DI\Injectable 的组件中方便的访问session服务,并且可方便的存储或获取它们的值。请看示例:

<?php

class UserController extends Phalcon\Mvc\Controller
{

    public function indexAction()
    {
        //Set a session variable
        $this->session->set("user-name", "Michael");
    }

    public function welcomeAction()
    {

        //Check if the variable is defined
        if ($this->session->has("user-name"))
        {

            //Retrieve its value
            $name = $this->session->get("user-name");
        }
    }

}

移除/销毁 Session数据

你可以移除指定的session数据,也可销毁整个session:

<?php

class UserController extends Phalcon\Mvc\Controller
{

    public function removeAction()
    {
        //Remove a session variable
        $this->session->remove("user-name");
    }

    public function logoutAction()
    {
        //Destroy the whole session
        $this->session->destroy();
    }

}

Isolating Session Data between Applications

有时,我们可能部署相同的应用程序在同一台服务器上两次,而使用相同的会话。当然,如果我们在会话中使用变量,我们希望每个应用程序都有其单独的会话数据(即使相同代码和相同的变量名称)。为了解决这个问题,你可以在某个应用程序中为每个会话创建的变量添加一个前辍:

<?php

//Isolating the session data
$di->set('session', function(){

    //All variables created will prefixed with "my-app-1"
    $session = new Phalcon\Session\Adapter\Files(
        array(
            'uniqueId' => 'my-app-1'
        )
    );

    $session->start();

    return $session;
});

Session Bags

Phalcon\Session\Bag 组件帮助把session数据导入到 “namespaces”。通过这种方式,你可以轻松的创建一组会话变量到应用程序中,只需设置变量为 “bag”,它会自动存储为session数据:

<?php

$user       = new Phalcon\Session\Bag();
$user->name = "Kimbra Johnson";
$user->age  = 22;

Persistent Data in Components

控制器,组件,或者其他继承自 Phalcon\DI\Injectable 的类都可以注入到 Phalcon\Session\Bag.使用这个类的会话数据在每个类中的变量是隔离开的,基于此,你可以隔离每个请求持久化数据。

译者注: 我曾在翻译tutorial invo章节时测试过此属性,并添加了注释。可以查阅 tutorial-invo,搜索 ‘译者注’查看

<?php

class UserController extends Phalcon\Mvc\Controller
{

    public function indexAction()
    {
        // Create a persistent variable "name"
        $this->persistent->name = "Laura";
    }

    public function welcomeAction()
    {
        if (isset($this->persistent->name))
        {
            echo "Welcome, ", $this->persistent->name;
        }
    }

}

In a component:

<?php

class Security extends Phalcon\Mvc\User\Component
{

    public function auth()
    {
        // Create a persistent variable "name"
        $this->persistent->name = "Laura";
    }

    public function getAuthName()
    {
        return $this->persistent->name;
    }

}

通过 ($this->session) 添加的变量,可在整个应用程序进行访问。而通过 ($this->persistent) 添加的变量,只能在当前类访问。

实现自定义适配器

The Phalcon\Session\AdapterInterface interface must be implemented in order to create your own translate adapters or extend the existing ones:

<?php

class MySessionHandler implements Phalcon\Session\AdapterInterface
{

    /**
     * MySessionHandler construtor
     *
     * @param array $options
     */
    public function __construct($options=null)
    {
    }

    /**
     * Starts session, optionally using an adapter
     *
     * @param array $options
     */
    public function start()
    {
    }

    /**
     * Sets session options
     *
     * @param array $options
     */
    public function setOptions($options)
    {
    }

    /**
     * Get internal options
     *
     * @return array
     */
    public function getOptions()
    {
    }

    /**
     * Gets a session variable from an application context
     *
     * @param string $index
     */
    public function get($index)
    {
    }

    /**
     * Sets a session variable in an application context
     *
     * @param string $index
     * @param string $value
     */
    public function set($index, $value)
    {
    }

    /**
     * Check whether a session variable is set in an application context
     *
     * @param string $index
     */
    public function has($index)
    {
    }

    /**
     * Removes a session variable from an application context
     *
     * @param string $index
     */
    public function remove($index)
    {
    }

    /**
     * Returns active session id
     *
     * @return string
     */
    public function getId()
    {
    }

    /**
     * Check whether the session has been started
     *
     * @return boolean
     */
    public function isStarted()
    {
    }

    /**
     * Destroys the active session
     *
     * @return boolean
     */
    public function destroy()
    {
    }

}

Filtering and Sanitizing

对用户输入的数据进行过滤/消毒是软件开发的重要组成部分。过分信任或忽略过滤用户输入,可能导致用户访问到未经授权的页面,主要是用户数据,甚至是你应用程序的服务器托管的所有内容。

_images/sql.png

Full image (from xkcd)

Phalcon\Filter 组件提供了一组常用的用于过滤以及处理用户输入数据的助手工具。它提供了一种面像对象的方式来包装PHP filter扩展。

Sanitizing data

Sanitizing 处理从字符串中移除指定字符,这并不是必须的,需要开发者明确指定。sanitizing后的用户输入数据,能确保应用程序的完整和安全。

<?php

$filter = new \Phalcon\Filter();

// returns "someone@example.com"
$filter->sanitize("some(one)@exa\mple.com", "email");

// returns "hello"
$filter->sanitize("hello<<", "string");

// returns "100019"
$filter->sanitize("!100a019", "int");

// returns "100019.01"
$filter->sanitize("!100a019.01a", "float");

Sanitizing from Controllers

你可以在控制器中访问 Phalcon\Filter 对象,当需要访问GET或POST输入数据时(通过request对象)。第一个参数是变量的名称,第二个参数是filter类型。

<?php

class ProductsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function saveAction()
    {

        // Sanitizing price from input
        $price = $this->request->getPost("price", "double");

        // Sanitizing email from input
        $email = $this->request->getPost("customerEmail", "email");

    }

}

Filtering Action Parameters

下面的示例将向你展示如何在controller/action中 sanitize Action的参数:

<?php

class ProductsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function showAction($productId)
    {
        $productId = $this->filter->sanitize($productId, "int");
    }

}

Filtering data

除了sanitizing功能,Phalcon\Filter 还提供了删除或修改输入数据的过滤功能,以生成我们想要的数据。

<?php

$filter = new \Phalcon\Filter();

// returns "Hello"
$filter->filter("<h1>Hello</h1>", "striptags");

// returns "Hello"
$filter->filter("  Hello   ", "trim");

Filters内置类型

The following are the built-in filters provided by this component:

Name Description
string Strip tags
email Remove all characters except letters, digits and !#$%&*+-/=?^_`{|}~@.[].
int Remove all characters except digits, plus and minus sign.
float Remove all characters except digits, dot, plus and minus sign.
alphanum Remove all characters except [a-zA-Z0-9]
striptags Applies the strip_tags function
trim Applies the trim function
lower Applies the strtolower function
upper Applies the strtoupper function

自定义Filters

你可以创建自定义过滤器添加到 Phalcon\Filter。过滤函数可以使用匿名函数的形式:

<?php

$filter = new \Phalcon\Filter();

//Using an anonymous function
$filter->add('md5', function($value) {
    return preg_replace('/[^0-9a-f]/', '', $value);
});

//Sanitize with the "md5" filter
$filtered = $filter->sanitize($possibleMd5, "md5");

或者,如果你愿意,你也可以实现一个过滤器类:

<?php

class IPv4Filter
{

    public function filter($value)
    {
        return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
    }

}

$filter = new \Phalcon\Filter();

//Using an object
$filter->add('ipv4', new IPv4Filter());

//Sanitize with the "ipv4" filter
$filteredIp = $filter->sanitize("127.0.0.1", "ipv4");

Complex Sanitizing and Filtering

PHP本身也提供了一个极好的filter扩展,查阅文档:Data Filtering at PHP Documentation

Implementing your own Filter

The Phalcon\FilterInterface interface must be implemented to create your own filtering service replacing the one providing by Phalcon.

Reading Configuration

Phalcon\Config 使用相应的适配器读取配置文件,转换为面像对象的方式进行操作配置文件。

File Adapters

可用的适配器:

File Type Description
Ini Uses INI files to store settings. Internally the adapter uses the PHP function parse_ini_file.
Array Uses PHP multidimensional arrays to store settings. This adapter offers the best performance.

原生数组

下面的示例演示了如何把原生PHP数组转化为 Phalcon\Config 对象。下面的示例提供了最佳性能,因为在此请求期间,未发生文件读取。

<?php

$settings = array(
    "database" => array(
        "adapter"  => "Mysql",
        "host"     => "localhost",
        "username" => "scott",
        "password" => "cheetah",
        "name"     => "test_db",
    ),
     "app" => array(
        "controllersDir" => "../app/controllers/",
        "modelsDir"      => "../app/models/",
        "viewsDir"       => "../app/views/",
    ),
    "mysetting" => "the-value"
);

$config = new \Phalcon\Config($settings);

echo $config->app->controllersDir, "\n";
echo $config->database->username, "\n";
echo $config->mysetting, "\n";

如果你想更好的组织你的项目结构,你可以把数组保存到一个单独的文件中,然后读取它。

<?php

require "config/config.php";
$config = new \Phalcon\Config($settings);

读取INI文件

INI文件是一种常见的方式来存储设置。Phalcon\Config 使用优化的PHP函数parse_ini_file读取这些文件。INI文件中的sections部分被解析成子设定,以方便使用。

[database]
adapter  = Mysql
host     = localhost
username = scott
password = cheetah
name     = test_db

[phalcon]
controllersDir = "../app/controllers/"
modelsDir      = "../app/models/"
viewsDir       = "../app/views/"

[models]
metadata.adapter  = "Memory"

你可以按以下方式读取配件文件:

<?php

$config = new \Phalcon\Config\Adapter\Ini("path/config.ini");

echo $config->phalcon->controllersDir, "\n";
echo $config->database->username, "\n";
echo $config->models->metadata->adapter, "\n";

数据分页

当有一大组数据需要呈现时,我们需要用到数据分页。Phalcon\Paginator 提供了一个快捷,方便的方法对大组数据进行分割,以达到分页浏览的效果。

Data Adapters

这个组件使用不同的适配器来封装不同的数据源:

Adapter Description
NativeArray Use a PHP array as source data
Model Use a Phalcon\Model\Resultset object as source data

Using Paginators

在下面的例子中,paginator将从model中读取数据作为其数据源,并限制每页显示10条记录:

<?php

// Current page to show
// In a controller this can be:
// $this->request->getQuery('page', 'int'); // GET
// $this->request->getPost('page', 'int'); // POST
$currentPage = (int) $_GET["page"];

// The data set to paginate
$robots = Robots::find();

// Create a Model paginator, show 10 rows by page starting from $currentPage
$paginator = new Phalcon\Paginator\Adapter\Model(
    array(
        "data" => $robots,
        "limit"=> 10,
        "page" => $currentPage
    )
);

// Get the paginated results
$page = $paginator->getPaginate();

变量 $currentPage 控制将显示哪一页。 $paginator->getPaginate() 返回一个包含分页数据的 $page 对象,它将用于生成分页:

<table>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Type</th>
    </tr>
    <?php foreach($page->items as $item) { ?>
    <tr>
        <td><?php echo $item->id; ?></td>
        <td><?php echo $item->name; ?></td>
        <td><?php echo $item->type; ?></td>
    </tr>
    <?php } ?>
</table>

$page对象还包含以下数据:

<a href="/robots/search">First</a>
<a href="/robots/search?page=<?= $page->before; ?>">Previous</a>
<a href="/robots/search?page=<?= $page->next; ?>">Next</a>
<a href="/robots/search?page=<?= $page->last; ?>">Last</a>

<?php echo "You are in page ", $page->current, " of ", $page->total_pages; ?>

Page 属性

$page对象包含以下一些属性:

Adapter Description
items The set of records to be displayed at the current page
before The previous page to the current one
next The next page to the current one
last The last page in the set of records

实现自定义的分页适配器

The Phalcon\Paginator\AdapterInterface interface must be implemented in order to create your own paginator adapters or extend the existing ones:

<?php

class MyPaginator implements Phalcon\Paginator\AdapterInterface  {

    /**
     * Adapter constructor
     *
     * @param array $config
     */
    public function __construct($config);

    /**
     * Set the current page number
     *
     * @param int $page
     */
    public function setCurrentPage($page);

    /**
     * Returns a slice of the resultset to show in the pagination
     *
     * @return stdClass
     */
    public function getPaginate();

}

使用缓存提升性能

Phalcon 提供 Phalcon\Cache 类,以便更快的访问经常使用的数据或已经处理过的数据。 Phalcon\Cache 使用C语言编写,实现更高的性能,并减少系统开销。 这个类提供前端和后端两个组件,前端组件作为输入源或接口,后端提供存储选项。

什么时候使用缓存?

虽然这个组件是非常高效快速的,但如果使用不当,也有可能导致性能问题,从而得不偿失。 我们建议你在使用缓存之前检查以下情况:

  • 进行复杂的数据计算,每次返回相同的结果(不经常修改)
  • 使用了大量的助手工具,并且生成的输出几乎问题一样的
  • 不断的访问数据库,且这些数据很少改变
注意 即便已经使用了缓存,过一段时间后,你应该检查你的缓存的命中率,尤其你使用的是Memcache或者Apc时。使用后端提供的相关工具,很容易完成命中率检查。

缓存行为

缓存的执行分为两个部分:

  • Frontend: 这一部分主要负责检查KEY是否过期以及在存储到backend之前/从backend取数据之后执行额外的数据转换
  • Backend: 这部分主要负责沟通,并根据前端的需求读写数据。

片断缓存

片断缓存是缓存HTML或者TEXT文本的一部分,然后原样返回。输出自动捕获来自ob_* 函数或PHP输出,以便它可以保存到缓存中。 下面的例子演示了这种用法。 它接收PHP生成的输出,并将其存储到一个文件中,文件的内容172800秒(2天)更新一次。

这种缓存机制的实现,使我们既能获得性能,而又不执行Phalcon\Tag::linkTo的调用。

<?php

//Create an Output frontend. Cache the files for 2 days
$frontCache = new Phalcon\Cache\Frontend\Output(array(
    "lifetime" => 172800
));

// Create the component that will cache from the "Output" to a "File" backend
// Set the cache file directory - it's important to keep the "/" at the end of
// the value for the folder
$cache = new Phalcon\Cache\Backend\File($frontCache, array(
    "cacheDir" => "../app/cache/"
));

// Get/Set the cache file to ../app/cache/my-cache.html
$content = $cache->start("my-cache.html");

// If $content is null then the content will be generated for the cache
if ($content === null) {

    //Print date and time
    echo date("r");

    //Generate a link to the sign-up action
    echo Phalcon\Tag::linkTo(
        array(
            "user/signup",
            "Sign Up",
            "class" => "signup-button"
        )
    );

    // Store the output into the cache file
    $cache->save();

} else {

    // Echo the cached output
    echo $content;
}

NOTE In the example above, our code remains the same, echoing output to the user as it has been doing before. 缓存组件透明的捕获该输出,并将其存储到缓存文件中(前提是已经生成cache对象),或将其之前的缓存发送给用户,从而避免代价昂贵的开销。

Caching Arbitrary Data

缓存是应用程序重要的组成部分。缓存可以减少数据库负载,重复使用常用的数据(但不更新),从而加快了您的应用程序。

File Backend Example

缓存适配器之一’File’,此适配器的属性只有一个,它用来指定缓存文件的存储位置。使用 cacheDir选项进行控制,且 必须 以’/’结尾。

<?php

// Cache the files for 2 days using a Data frontend
$frontCache = new Phalcon\Cache\Frontend\Data(array(
    "lifetime" => 172800
));

// Create the component that will cache "Data" to a "File" backend
// Set the cache file directory - important to keep the "/" at the end of
// of the value for the folder
$cache = new Phalcon\Cache\Backend\File($frontCache, array(
    "cacheDir" => "../app/cache/"
));

// Try to get cached records
$cacheKey = 'robots_order_id.cache';
$robots    = $cache->get($cacheKey);
if ($robots === null) {

    // $robots is null because of cache expiration or data does not exist
    // Make the database call and populate the variable
    $robots = Robots::find(array("order" => "id"));

    // Store it in the cache
    $cache->save($cacheKey, $robots);
}

// Use $robots :)
foreach ($robots as $robot) {
   echo $robot->name, "\n";
}
Memcached Backend Example

上面的例子稍微改变一下(主要是配置方面),就可以使用Memcache做为后端存储器了。

<?php

//Cache data for one hour
$frontCache = new Phalcon\Cache\Frontend\Data(array(
    "lifetime" => 3600
));

// Create the component that will cache "Data" to a "Memcached" backend
// Memcached connection settings
$cache = new Phalcon\Cache\Backend\Memcached($frontCache, array(
    "host" => "localhost",
    "port" => "11211"
));

// Try to get cached records
$cacheKey = 'robots_order_id.cache';
$robots    = $cache->get($cacheKey);
if ($robots === null) {

    // $robots is null because of cache expiration or data does not exist
    // Make the database call and populate the variable
    $robots = Robots::find(array("order" => "id"));

    // Store it in the cache
    $cache->save($cacheKey, $robots);
}

// Use $robots :)
foreach ($robots as $robot) {
   echo $robot->name, "\n";
}

Querying the cache

缓存唯一标识符元素为KEY,在后端文件中,KEY值即是实际文件名。从缓存中检索数据,我们只需要通过KEY来调用即可。如果该KEY不存在,get方法将返回null。

<?php

// Retrieve products by key "myProducts"
$products = $cache->get("myProducts");

如果你想知道缓存中都有哪些KEY,你可以调用queryKeys方法:

<?php

// Query all keys used in the cache
$keys = $cache->queryKeys();
foreach ($keys as $key) {
    $data = $cache->get($key);
    echo "Key=", $key, " Data=", $data;
}

//Query keys in the cache that begins with "my-prefix"
$keys = $cache->queryKeys("my-prefix");

删除缓存数据

很多时候,你需要强行删除无效的缓存条目(由于数据更新的原因),唯一的要求就是,你得知道该缓存的KEY。

<?php

// Delete an item with a specific key
$cache->queryKeys("someKey");

// Delete all items from the cache
$keys = $cache->queryKeys();
foreach ($keys as $key) {
    $cache->delete($key);
}

检测缓存是否存在

通过给定的KEY值,可以检测缓存是否存在。

<?php

if ($cache->exists("someKey")) {
    echo $cache->get("someKey");
}
else {
    echo "Cache does not exists!";
}

前端适配器

The available frontend adapters that are used as interfaces or input sources to the cache are:

Adapter Description Example
Output Read input data from standard PHP output Phalcon\Cache\Frontend\Output
Data It’s used to cache any kind of PHP data (big arrays, objects, text, etc). The data is serialized before stored in the backend. Phalcon\Cache\Frontend\Data
Base64 It’s used to cache binary data. The data is serialized using base64_encode before be stored in the backend. Phalcon\Cache\Frontend\Base64
None It’s used to cache any kind of PHP data without serializing them. Phalcon\Cache\Frontend\Data
实现自定义的前端适配器

The Phalcon\Cache\FrontendInterface interface must be implemented in order to create your own frontend adapters or extend the existing ones.

后端适配器

可用的后端存储器列表:

Adapter Description Info Required Extensions Example
File Stores data to local plain files     Phalcon\Cache\Backend\File
Memcached Stores data to a memcached server Memcached memcache Phalcon\Cache\Backend\Memcache
APC Stores data to the Alternative PHP Cache (APC) APC APC extension Phalcon\Cache\Backend\Apc
Mongo Stores data to Mongo Database MongoDb Mongo Phalcon\Cache\Backend\Mongo
实现自定义后端适配器

The Phalcon\Cache\BackendInterface interface must be implemented in order to create your own backend adapters or extend the existing ones.

文件缓存选项

This backend will store cached content into files in the local server. The available options for this backend are:

Option Description
cacheDir A writable directory on which cached files will be placed
Memcached缓存选项

This backend will store cached content on a memcached server. The available options for this backend are:

Option Description
host memcached host
port memcached port
persistent create a persitent connection to memcached?
APC缓存选项

This backend will store cached content on Alternative PHP Cache (APC). This cache backend does not require any additional configuration options.

Mongo缓存选项

This backend will store cached content on a MongoDB server. The available options for this backend are:

Option Description
server A MongoDB connection string
db Mongo database name
collection Mongo collection in the database

Access Control Lists ACL

Phalcon\Acl provides an easy and lightweight management of ACLs as well as the permissions attached to them. Access Control Lists (ACL) allow an application to control access to its areas and the underlying objects from requests. You are encouraged to read more about the ACL methodology so as to be familiar with its concepts.

In summary, ACLs have roles and resources. Resources are objects which abide by the permissions defined to them by the ACLs. Roles are objects that request access to resources and can be allowed or denied access by the ACL mechanism.

Creating an ACL

This component is designed to initially work in memory. This provides ease of use and speed in accessing every aspect of the list. The Phalcon\Acl constructor takes as its first parameter an adapter used to retriever the information related to the control list. An example using the memory adapter is below:

<?php $acl = new \Phalcon\Acl\Adapter\Memory();

By default Phalcon\Acl allows access to action on resources that have not been yet defined. To increase the security level of the access list we can define a “deny” level as a default access level.

<?php

// Default action is deny access
$acl->setDefaultAction(Phalcon\Acl::DENY);

Adding Roles to the ACL

A role is an object that can or cannot access certain resources in the access list. As an example, we will define roles as groups of people in an organization. The Phalcon\Acl\Role class is available to create roles in a more structured way. Let’s add some roles to our recently created list:

<?php

// Create some roles
$roleAdmins = new \Phalcon\Acl\Role("Administrators", "Super-User role");
$roleGuests = new \Phalcon\Acl\Role("Guests");

// Add "Guests" role to acl
acl->addRole($roleGuests);

// Add "Designers" role to acl without a Phalcon\Acl\Role
$acl->addRole("Designers");

As you can see, roles are defined directly without using a instance.

Adding Resources

Resources are objects where access is controlled. Normally in MVC applications resources refer to controllers. Although this is not mandatory, the Phalcon\Acl\Resource class can be used in defining resources. It’s important to add related actions or operations to a resource so that the ACL can understand what it should to control.

<?php

// Define the "Customers" resource
$customersResource = new \Phalcon\Acl\Resource("Customers");

// Add "customers" resource with a couple of operations
$acl->addResource($customersResource, "search");
$acl->addResource($customersResource, array("create", "update"));

Defining Access Controls

Now we’ve roles and resources. It’s time to define the ACL i.e. which roles can access which resources. This part is very important especially taking in consideration your default access level “allow” or “deny”.

<?php

// Set access level for roles into resources
$acl->allow("Guests", "Customers", "search");
$acl->allow("Guests", "Customers", "create");
$acl->deny("Guests", "Customers", "update");

The allow method designates that a particular role has granted access to access a particular resource. The deny method does the opposite.

Querying an ACL

Once the list has been completely defined. We can query it to check if a role has a given permission or not.

<?php

// Check whether role has access to the operations
$acl->isAllowed("Guests", "Customers", "edit");   //Returns 0
$acl->isAllowed("Guests", "Customers", "search"); //Returns 1
$acl->isAllowed("Guests", "Customers", "create"); //Returns 1

Roles Inheritance

You can build complex role structures using the inheritance that Phalcon\Acl\Role provides. Roles can inherit from other roles, thus allowing access to supersets or subsets of resources. To use role inheritance, you need to pass the inherited role as the second parameter of the function call, when adding that role in the list.

<?php

// Create some roles
$roleAdmins = new \Phalcon\Acl\Role("Administrators", "Super-User role");
$roleGuests = new \Phalcon\Acl\Role("Guests");

// Add "Guests" role to acl
$acl->addRole($roleGuests);

// Add "Administrators" role inheriting from "Guests" its accesses
$acl->addRole($roleAdmins, $roleGuests);

Serializing ACL lists

To improve performance Phalcon\Acl instances can be serialized and stored in text files or a database table so that they can be loaded at will without having to redefine the whole list. You can do that as follows:

<?php

//Check whether acl data already exist
if (!file_exists("app/security/acl.data")) {

    $acl = new \Phalcon\Acl("Memory");

    //... Define roles, resources, access, etc

    // Store serialized list into plain file
    file_put_contents("app/security/acl.data", serialize($acl));

} else {

     //Restore acl object from serialized file
     $acl = unserialize(file_get_contents("app/security/acl.data"));
}

// Use acl list as needed
if ($acl->isAllowed("Guests", "Customers", "edit")) {
    echo "Access granted!";
} else {
    echo "Access denied :(";
}

Acl Events

Phalcon\Acl is able to send events to a EventsManager if it’s present. Events are triggered using the type “acl”. Some events when returning boolean false could stop the active operation. The following events are supported:

Event Name Triggered Can stop operation?
beforeCheckAccess Triggered before check if a role/resource has access Yes
afterCheckAccess Triggered after check if a role/resource has access No

The following example demonstrates how to attach listeners to this component:

<?php

//Create an event manager
$eventsManager = new Phalcon\Events\Manager();

//Attach a listener for type "acl"
$eventsManager->attach("acl", function($event, $acl) {
    if ($event->getType() == 'beforeCheckAccess') {
         echo   $acl->getActiveRole(),
                $acl->getActiveResource(),
                $acl->getActiveAccess();
    }
});

$acl = new \Phalcon\Acl\Adapter\Memory();

//Setup the $acl
//...

//Bind the eventsManager to the acl component
$acl->setEventsManager($eventManagers);

Implementing your own adapters

The Phalcon\Acl\AdapterInterface interface must be implemented in order to create your own ACL adapters or extend the existing ones.

多语言支持

在应用程序开发中,可使用:doc:Phalcon\Translate <../api/Phalcon_Translate> 组件帮助实现多语言。使用此组件,可根据用户选择的语言提供相应的语言支持。

适配器

该组件使用适配器,以统一的方式读取相应的语言文件。

Adapter Description
NativeArray Uses PHP arrays to store the messages. This is the best option in terms of performance.

Component Usage

翻译的字符串存储在文件中,这些文件的结构可能会有所不同,具体取决于你所使用的适配器。Phalcon允许你自由的组织翻译,简单的结构可能是这样:

app/messages/en.php
app/messages/es.php
app/messages/fr.php
app/messages/zh.php

每个翻译文件都包含一个由key/value组成的数组。对于每一个翻译文件,key都是唯一的,相同的数组需要使用不同的文件,保持key不变,value值根据每种语言进行翻译即可。

<?php

//app/messages/es.php
$messages = array(
    "hi"      => "Hello",
    "bye"     => "Good Bye",
    "hi-name" => "Hello %name%",
    "song"    => "This song is %song%"
);
<?php

//app/messages/fr.php
$messages = array(
    "hi"      => "Bonjour",
    "bye"     => "Au revoir",
    "hi-name" => "Bonjour %name%",
    "song"    => "La chanson est %song%"
);

在应用程序中实现语言转化机制并不难,关键取决于你想如何实现它。你可以根据检测用户的浏览器语言为用户提供相应的语言支持或者提供一个设置页面供用户自己选择他们想要的语言。

一个简单的用于检测客户端用户语言的方式是通过 $_SERVER[‘HTTP_ACCEPT_LANGUAGE’],或者也可以在controller/action中直接调用 $this->request->getBestLanguage() 也可。

<?php

class UserController extends \Phalcon\Mvc\Controller
{

  protected function _getTranslation()
  {

    //Ask browser what is the best language
    $language = $this->request->getBestLanguage();

    //Check if we have a translation file for that lang
    if (file_exists("app/messages/".$language.".php")) {
       require "app/messages/".$language.".php";
    } else {
       // fallback to some default
       require "app/messages/en.php";
    }

    //Return a translation object
    return new \Phalcon\Translate\Adapter\NativeArray(array(
       "content" => $messages
    ));

  }

  public function indexAction()
  {
    $this->view->setVar("name", "Mike");
    $this->view->setVar("t", $this->_getTranslation());
  }

}

本例中的 _getTranslation 适用于整个控制器,通过变量 $t 传递翻译字符到视图,并且使用它。我们可以在视图层这样使用翻译字符串:

<!-- welcome -->
<!-- String: hi => 'Hello' -->
<p><?php echo $t->_("hi"), " ", $name; ?></p>

函数”_”通过传递的key返回翻译后的字符串。一些字符串中可能包含有占位符,如 Hello %name%。这些点位符可以通过函数”_”来传递参数进行替换,传递的参数是一个key/value的数组,其中的key是占位符名称,值是被替换的数据:

<!-- welcome -->
<!-- String: hi-user => 'Hello %name%' -->
<p><?php echo $t->_("hi-user", array("name" => $name)); ?></p>

一些应用程序实现了基于URL的多语言,如 http://www.mozilla.org/es-ES/firefox/. Phalcon 通过使用 Router 也可以实现一样的效果。

Implementing your own adapters

The Phalcon\Translate\AdapterInterface interface must be implemented in order to create your own translate adapters or extend the existing ones:

<?php

class MyTranslateAdapter implements Phalcon\Translate\AdapterInterface
{

    /**
     * Adapter constructor
     *
     * @param array $data
     */
    public function __construct($options);

    /**
     * Returns the translation string of the given key
     *
     * @param   string $translateKey
     * @param   array $placeholders
     * @return  string
     */
    public function _($translateKey, $placeholders=null);

    /**
     * Returns the translation related to the given key
     *
     * @param   string $index
     * @param   array $placeholders
     * @return  string
     */
    public function query($index, $placeholders=null);

    /**
     * Check whether is defined a translation key in the internal array
     *
     * @param   string $index
     * @return  bool
     */
    public function exists($index);

}

万能的类文件加载器

Phalcon\Loader 这个组件允许你根据预定义规则自动加载项目中的类文件。 此组件采用C语言编写,在读取和解析PHP文件方面,使用了最低的性能开销。

此组件功能是基于PHP自身的 autoloading classes 实现的。如果在任何代码部分未找到类,那么它将尝试使用特殊的处理加载它,:doc:Phalcon\Loader <../api/Phalcon_Loader> 就是用于处理这种任务的。加载类文件采用按需加载的方式,只有需要某个类文件时,才会进行加载及文件读取。这种技术被称为延时初始化( lazy initialization )。

使用此组件,你可以从其他项目或vendors(不知道是什么,应该指的是其他服务器)加载文件,autoloader 采用 PSR-0 标准。

Phalcon\Loader 提供四种方式自动加载类文件,你可以一次只使用其中一个,或者混合使用。

Registering Namespaces

如果你的代码使用了命名空间或外部库文件,可以使用registerNamespaces(),它提供了一种自动加载机制,可以通过传递一个关联数组,key是命名空间前辍,value是类文件存放的目录。当加载并试图查找类文件时,分隔符被替换成目录分隔符,以便正确加载类文件。还有一点请注意,value末尾一定要以”/”结尾。

<?php

// Creates the autoloader
$loader = new \Phalcon\Loader();

//Register some namespaces
$loader->registerNamespaces(
    array(
       "Example\Base"    => "vendor/example/base/",
       "Example\Adapter" => "vendor/example/adapter/",
       "Example"         => "vendor/example/",
    )
);

// register autoloader
$loader->register();

// The required class will automatically include the
// file vendor/example/adapter/Some.php
$some = new Example\Adapter\Some();

Registering Prefixes

这种策略非常类似上面讲到的命名空间的加载机制。它也需要一个关联数组,key是前辍,value是类所在的目录。加载的时候,命名空间分隔符和下划线”_”将要被替换为目录分隔符。还是请注意,value的结尾一定要以”/”作为结束符。

<?php

// Creates the autoloader
$loader = new \Phalcon\Loader();

//Register some prefixes
$loader->registerPrefixes(
    array(
       "Example_Base"    => "vendor/example/base/",
       "Example_Adapter" => "vendor/example/adapter/",
       "Example_"         => "vendor/example/",
    )
);

// register autoloader
$loader->register();

// The required class will automatically include the
// file vendor/example/adapter/Some.php
$some = new Example_Adapter_Some();

Registering Directories

第三种方式是注册目录,在注册的目录中找到类文件。在性能方面,不建议使用此种方式,因为Phalcon将对注册的所有目录及文件进行查找,直接查找具有相同名称的类文件。注册目录时的顺序是非常重要的。请注意,结尾以”/”结束。

<?php

// Creates the autoloader
$loader = new \Phalcon\Loader();

// Register some directories
$loader->registerDirs(
    array(
        "library/MyComponent/",
        "library/OtherComponent/Other/",
        "vendor/example/adapters/",
        "vendor/example/"
    )
);

// register autoloader
$loader->register();

// The required class will automatically include the file from
// the first directory where it has been located
// i.e. library/OtherComponent/Other/Some.php
$some = new Some();

Registering Classes

最后一种方式是注册类的名称和路径。这种加载方面是最快的一种加载方式。然而,随着应用程序的增长,更多的类及文件需要加载,这将使维护工作变得非常麻烦,因为不太建议使用。

<?php

// Creates the autoloader
$loader = new \Phalcon\Loader();

// Register some classes
$loader->registerClasses(
    array(
        "Some"         => "library/OtherComponent/Other/Some.php",
        "Example\Base" => "vendor/example/adapters/Example/BaseClass.php",
    )
);

// register autoloader
$loader->register();

// Requiring a class will automatically include the file it references
// in the associative array
// i.e. library/OtherComponent/Other/Some.php
$some = new Some();

其他扩展名文件的加载

一些自动加载策略,如”prefixes”,”namespaces”,或”directories”都会自动加载扩展名为”.php”的文件。如果你想自动加载其他扩展类型的文件时,你可以使用”setExtensions”方法。示例如下:

<?php

 // Creates the autoloader
$loader = new \Phalcon\Loader();

//Set file extensions to check
$loader->setExtensions(array("php", "inc", "phb"));

Modifying current strategies

通过下面的方式可以把需要后来加载的其他文件合并到上述加载策略中:

<?php

// Adding more directories
$loader->registerDirs(
    array(
        "../app/library/"
        "../app/plugins/"
    ),
    true
);

通过传递第二个参数”true”,可以让新的目录或类文件合并到上述四种加载策略中。

Autoloading Events

在下面的例子中,EventsManager与类加载器协同工作,使我们能够获得操作流程的调试信息:

<?php

$eventsManager = new \Phalcon\Events\Manager();

$loader = new \Phalcon\Loader();

$loader->registerNamespaces(array(
   'Example\\Base' => 'vendor/example/base/',
   'Example\\Adapter' => 'vendor/example/adapter/',
   'Example' => 'vendor/example/'
));

//Listen all the loader events
$eventsManager->attach('loader', function($event, $loader) {
    if ($event->getType() == 'beforeCheckPath') {
        echo $loader->getCheckedPath();
    }
});

$loader->setEventsManager($eventsManager);

$loader->register();

当事件返回布尔值false时,可以停止激活的操作。支持以下一些事件:

Event Name Triggered Can stop operation?
beforeCheckClass Triggered before start the autoloading process Yes
pathFound Triggered when the loader locate a class No
afterCheckClass Triggered after finish the autoloading process. If this event is launched the autoloader didn’t find the class file No

Logging

Phalcon\Logger is a component whose purpose is to provide logging services for applications. It offers logging to different backends using different adapters. It also offers transaction logging, configuration options, different formats and filters. You can use the Phalcon\Logger for every logging need your application has, from debugging processes to tracing application flow.

Adapters

This component makes use of backend adapters to store data. The use of adapters allows for a common interface for logging while switching backends if necessary. The backends supported are:

Adapter Description API
File Logs to a plain text file Phalcon\Logger\Adapter\File

Creating a Log

The example below shows how to create a log and add messages to it:

<?php

$logger = new \Phalcon\Logger\Adapter\File("app/logs/test.log");
$logger->log("This is a message");
$logger->log("This is an error", \Phalcon\Logger::ERROR);
$logger->error("This is another error");
$logger->close();

The log generated is below:

[Tue, 17 Apr 12 22:09:02 -0500][DEBUG] This is a message
[Tue, 17 Apr 12 22:09:02 -0500][ERROR] This is an error
[Tue, 17 Apr 12 22:09:02 -0500][ERROR] This is another error

Transactions

Logging data to an adapter i.e. File (file system) is always an expensive operation in terms of performance. To combat that, you can take advantage of logging transactions. Transactions store log data temporarily in memory and later on write the data to the relevant adapter (File in this case) in a single atomic operation.

<?php

// Create the logger
$logger = new \Phalcon\Logger\Adapter\File("app/logs/test.log");

// Start a transaction
$logger->begin();

// Add messages
$logger->alert("This is an alert");
$logger->error("This is another error");

// Commit messages to file
$logger->commit();

$logger->close();

Message Formatting

The default logging format is:

[%date%][%type%] %message%

PhalconLogger offers the setFormat() method, which allows you to change the format of the logged messages by defining your own. The log format variables allowed are:

Variable Description
%message% The message itself expected to be logged
%date% Date the message was added
%type% Uppercase string with message type

The example below shows how to change the log format:

<?php

//Changing the logger format
$logger->setFormat("%date% - %message%");

File Logger

This logger uses plain files to log any kind of data. File handlers are internally open with function fopen. By default all logger files are open using ‘ab’ mode which open the files for writing only; placing the file pointer at the end of the file. If the file does not exist, attempt to create it. You can change this mode passing additional options to the constructor:

<?php

// Create the file logger in 'w' mode
$logger = new \Phalcon\Logger\Adapter\File("app/logs/test.log", array(
    'mode' => 'w'
));

Implementing your own adapters

The Phalcon\Logger\AdapterInterface interface must be implemented in order to create your own logger adapters or extend the existing ones.

命令行程序

命令行程序是指在命名行下执行的程序,他们通常用来创建定时(cron)任务,脚本,命令行式实用程序或其他。

Tasks

Tasks are similar to controllers, on them can be implemented

<?php

class MonitoringTask extends \Phalcon\CLI\Task
{

    public function mainAction()
    {

    }

}
<?php

//Using the CLI factory default services container
$di = new Phalcon\DI\FactoryDefault\CLI();

//Create a console application
$console = new \Phalcon\CLI\Console();
$console->setDI($di);

//
$console->handle(array('shell_script_name', 'echo'));

Database Abstraction Layer

Phalcon\Db is the component behind Phalcon\Mvc\Model that powers the model layer in the framework. It consists of an independent high-level abstraction layer for database systems completely written in C.

This component allows for a lower level database manipulation than using traditional models.

This guide is not intended to be a complete documentation of available methods and their arguments. Please visit the API for a complete reference.

Database Adapters

This component makes use of adapters to encapsulate specific database system details. Phalcon uses PDO to connect to databases. The following database engines are supported:

Name Description API
MySQL Is the world’s most used relational database management system (RDBMS) that runs as a server providing multi-user access to a number of databases Phalcon\Db\Adapter\Pdo\Mysql
PostgreSQL PostgreSQL is a powerful, open source relational database system. It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. Phalcon\Db\Adapter\Pdo\Postgresql
SQLite SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine Phalcon\Db\Adapter\Pdo\Sqlite
Implementing your own adapters

The Phalcon\Db\AdapterInterface interface must be implemented in order to create your own database adapters or extend the existing ones.

Database Dialects

Phalcon encapsulates the specific details of each database engine in dialects. Those provide common functions and SQL generator to the adapters.

Name Description API
MySQL SQL specific dialect for MySQL database system Phalcon\Db\Dialect\Mysql
PostgreSQL SQL specific dialect for PostgreSQL database system Phalcon\Db\Dialect\Postgresql
SQLite SQL specific dialect for SQLite database system Phalcon\Db\Dialect\Sqlite

Connecting to Databases

To create a connection it’s neccesary instantiate the adapter class. It only requires an array with the connection parameters. The example below shows how to create a connection passing both required and optional parameters:

Implementing your own dialects

The Phalcon\Db\DialectInterface interface must be implemented in order to create your own database dialects or extend the existing ones.

<?php

// Required
$config = array(
    "host" => "127.0.0.1",
    "username" => "mike",
    "password" => "sigma",
    "dbname" => "test_db"
);

// Optional
$config["persistent"] = false;

// Create a connection
$connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
<?php

// Required
$config = array(
    "host" => "localhost",
    "username" => "postgres",
    "password" => "secret1",
    "dbname" => "template"
);

// Optional
$config["schema"] = "public";

// Create a connection
$connection = new \Phalcon\Db\Adapter\Pdo\Postgresql($config);
<?php

// Required
$config = array(
    "dbname" => "/path/to/database.db"
);

// Create a connection
$connection = new \Phalcon\Db\Adapter\Pdo\Sqlite($config);

Finding Rows

Phalcon\Db provides several methods to query rows from tables. The specific SQL syntax of the target database engine is required in this case:

<?php

$sql = "SELECT id, name FROM robots ORDER BY name";

// Send a SQL statement to the database system
$result = $connection->query($sql);

// Print each robot name
while ($robot = $result->fetch()) {
   echo $robot["name"];
}

// Get all rows in an array
$robots = $connection->fetchAll($sql);
foreach ($robots as $robot) {
   echo $robot["name"];
}

// Get only the first row
$robot = $connection->fetchOne($sql);

By default these calls create arrays with both associative and numeric indexes. You can change this behavior by using Phalcon\Db\Result::setFetchMode(). This method receives a constant, defining which kind of index is required.

Constant Description
Phalcon\Db::FETCH_NUM Return an array with numeric indexes
Phalcon\Db::FETCH_ASSOC Return an array with associative indexes
Phalcon\Db::FETCH_BOTH Return an array with both associative and numeric indexes
Phalcon\Db::FETCH_OBJ Return an object instead of an array
<?php

$sql = "SELECT id, name FROM robots ORDER BY name";
$result = $connection->query($sql);

$result->setFetchMode(Phalcon\Db::DB_NUM);
while ($robot = $result->fetch()) {
   echo $robot[0];
}

The Phalcon\Db::query() returns an instance of Phalcon\Db\Result\Pdo. These objects encapsulate all the functionality related to the returned resultset i.e. traversing, seeking specific records, count etc.

<?php

$sql = "SELECT id, name FROM robots";
$result = $connection->query($sql);

// Traverse the resultset
while ($robot = $result->fetch()) {
   echo $robot["name"];
}

// Seek to the third row
$result->seek(2);
$robot = $result->fetch();

// Count the resultset
echo $result->numRows();

Binding Parameters

Bound parameters is also supported in Phalcon\Db. Although there is a minimal performance impact by using bound parameters, you are encouraged to use this methodology so as to eliminate the possibility of your code being subject to SQL injection attacks. Both string and integer placeholders are supported. Binding parameters can simply be achieved as follows:

<?php

// Binding with numeric placeholders
$sql    = "SELECT * FROM robots WHERE name = ?1 ORDER BY name";
$sql    = $connection->bindParams($sql, array(1 => "Wall-E"));
$result = $connection->query($sql);

// Binding with named placeholders
$sql     = "INSERT INTO `robots`(name`, year) VALUES (:name:, :year:)";
$sql     = $connection->bindParams($sql, array("name" => "Astro Boy", "year" => 1952));
$success = $connection->query($sql);

When using numeric placeholders, you will need to define them as integers i.e. 1 or 2. In this case “1” or “2” are considered strings and not numbers, so the placeholder could not be successfully replaced. With any adapter data are automatically escaped using PDO Quote.

This function takes into account the connection charset, so its recommended to define the correct charset in the connection parameters or in your database server configuration, as a wrong charset will produce undesired effects when storing or retrieving data.

Also, you can pass your parameterers directly to the execute/query methods. In this case bound parameters are directly passed to PDO:

<?php

// Binding with PDO placeholders
$sql    = "SELECT * FROM robots WHERE name = ? ORDER BY name";
$result = $connection->query($sql, array(1 => "Wall-E"));

Inserting/Updating/Deleting Rows

To insert, update or delete rows, you can use raw SQL or use the preset functions provided by the class:

<?php

// Inserting data with a raw SQL statement
$sql     = "INSERT INTO `robots`(`name`, `year`) VALUES ('Astro Boy', 1952)";
$success = $connection->execute($sql);

//With placeholders
$sql     = "INSERT INTO `robots`(`name`, `year`) VALUES (?, ?)";
$success = $connection->execute($sql, array('Astroy Boy', 1952));

// Generating dynamically the necessary SQL
$success = $connection->insert(
   "robots",
   array("Astro Boy", 1952),
   array("name", "year")
);

// Updating data with a raw SQL statement
$sql     = "UPDATE `robots` SET `name` = 'Astro boy' WHERE `id` = 101";
$success = $connection->execute($sql);

//With placeholders
$sql     = "UPDATE `robots` SET `name` = ? WHERE `id` = ?";
$success = $connection->execute($sql, array('Astroy Boy', 101));

// Generating dynamically the necessary SQL
$success = $connection->update(
   "robots",
   array("name")
   array("New Astro Boy"),
   "id = 101"
);

// Deleting data with a raw SQL statement
$sql     = "DELETE `robots` WHERE `id` = 101";
$success = $connection->execute($sql);

//With placeholders
$sql     = "DELETE `robots` WHERE `id` = ?";
$success = $connection->execute($sql, array(101));

// Generating dynamically the necessary SQL
$success = $connection->delete("robots", "id = 101");

Database Events

Phalcon\Db is able to send events to a EventsManager if it’s present. Some events when returning boolean false could stop the active operation. The following events are supported:

Event Name Triggered Can stop operation?
afterConnect After a successfully connection to a database system No
beforeQuery Before send a SQL statement to the database system Yes
afterQuery After send a SQL statement to database system No
beforeDisconnect Before close a temporal database connection No

Bind a EventsManager to a connection is simple, Phalcon\Db will trigger the events with the type “db”:

<?php

$eventsManager = new Phalcon\Events\Manager();

//Listen all the database events
$eventsManager->attach('db', $dbListener);

$connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
    "host" => "localhost",
    "username" => "root",
    "password" => "secret",
    "dbname" => "invo"
));

//Assign the eventsManager to the db adapter instance
$connection->setEventsManager($eventsManager);

Profiling SQL Statements

Phalcon\Db includes a profiling component called Phalcon\Db\Profiler, that is used to analyze the performance of database operations so as to diagnose performance problems and discover bottlenecks.

Database profiling is really easy With Phalcon\Db\Profiler:

<?php

$eventsManager = new Phalcon\Events\Manager();

$profiler = new \Phalcon\Db\Profiler();

//Listen all the database events
$eventsManager->attach('db', function($event, $connection) use ($profiler) {
    if ($event->getType() == 'beforeQuery') {
        //Start a profile with the active connection
        $profiler->startProfile($connection->getSQLStatement());
    }
    if ($event->getType() == 'afterQuery') {
        //Stop the active profile
        $profiler->stopProfile();
    }
});

$sql = "SELECT buyer_name, quantity, product_name "
     . "FROM buyers "
     . "LEFT JOIN products ON buyers.pid = products.id";

// Execute a SQL statement
$connection->query($sql);

// Get the last profile in the profiler
$profile = $profiler->getLastProfile();

echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
echo "Start Time: ", $profile->getInitialTime(), "\n";
echo "Final Time: ", $profile->getFinalTime(), "\n";
echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";

You can also create your own profile class based on Phalcon\Db\Profiler to record real time statistics of the statements sent to the database system:

<?php

use \Phalcon\Db\Profiler as Profiler;
use \Phalcon\Db\Profiler\Item as Item;

class DbProfiler extends Profiler
{

    /**
     * Executed before the SQL statement will sent to the db server
     */
    public function beforeStartProfile(Item $profile)
    {
        echo $profile->getSQLStatement();
    }

    /**
     * Executed after the SQL statement was sent to the db server
     */
    public function afterEndProfile(Item $profile)
    {
        echo $profile->getTotalElapsedSeconds();
    }

}

//Create a EventsManager
$eventsManager = new Phalcon\Events\Manager();

//Create a listener
$dbProfiler = new DbProfiler();

//Attach the listener listening for all database events
$eventsManager->attach('db', $dbProfiler);

Logging SQL Statements

Using high-level abstraction components such as Phalcon\Db to access a database, it is difficult to understand which statements are sent to the database system. Phalcon\Logger interacts with Phalcon\Db, providing logging capabilities on the database abstraction layer.

<?php

$eventsManager = new Phalcon\Events\Manager();

$logger = new \Phalcon\Logger\Adapter\File("app/logs/db.log");

//Listen all the database events
$eventsManager->attach('db', function($event, $connection) use ($logger) {
    if ($event->getType() == 'beforeQuery') {
        $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
    }
});

//Assign the eventsManager to the db adapter instance
$connection->setEventsManager($eventsManager);

//Execute some SQL statement
$connection->insert(
    "products",
    array("Hot pepper", 3.50),
    array("name", "price")
);

As above, the file app/logs/db.log will contain something like this:

[Sun, 29 Apr 12 22:35:26 -0500][DEBUG][Resource Id #77] INSERT INTO products
(name, price) VALUES ('Hot pepper', 3.50)
Implementing your own Logger

You can implement your own logger class for database queries, by creating a class that implements a single method called “log”. The method needs to accept a string as the first argument. You can then pass your logging object to Phalcon\Db::setLogger(), and from then on any SQL statement executed will call that method to log the results.

Describing Tables and Databases

Phalcon\Db also provides methods to retrieve detailed information about tables and databases.

<?php

// Get tables on the test_db database
$tables = $connection->listTables("test_db");

// Is there a table robots in the database?
$exists = $connection->tableExists("robots");

// Get name, data types and special features of robots fields
$fields = $connection->describeTable("robots");
foreach ($fields as $field) {
    echo "Column Type: ", $field["Type"];
}

// Get indexes on the robots table
$indexes = $connection->describeIndexes("robots");
foreach ($indexes as $index) {
    print_r($index->getColumns());
}

// Get foreign keys on the robots table
$references = $connection->describeReferences("robots");
foreach ($references as $reference) {
    // Print referenced columns
    print_r($reference->getReferencedColumns());
}

A table description is very similar to the MySQL describe command, it contains the following information:

Index Description
Field Field’s name
Type Column Type
Key Is the column part of the primary key or an index?
Null Does the column allow null values?

Creating/Altering/Dropping Tables

Different database systems (MySQL, Postgresql etc.) offer the ability to create, alter or drop tables with the use of commands such as CREATE, ALTER or DROP. The SQL syntax differs based on which database system is used. Phalcon\Db offers a unified interface to alter tables, without the need to differentiate the SQL syntax based on the target storage system.

Creating Tables

The following example shows how to create a table:

<?php

use \Phalcon\Db\Column as Column;

$connection->createTable(
    "robots",
    null,
    array(
       "columns" => array(
            new Column(
                "id",
                array(
                    "type"          => Column::TYPE_INTEGER,
                    "size"          => 10,
                    "notNull"       => true,
                    "autoIncrement" => true,
                )
            ),
            new Column(
                "name",
                array(
                    "type"    => Column::TYPE_VARCHAR,
                    "size"    => 70,
                    "notNull" => true,
                )
            ),
            new Column(
                "year",
                array(
                    "type"    => Column::TYPE_INTEGER,
                    "size"    => 11,
                    "notNull" => true,
                )
            )
        )
    )
);

Phalcon\Db::createTable() accepts an associative array describing the table. Columns are defined with the class Phalcon\Db\Column. The table below shows the options available to define a column:

Option Description Optional
“type” Column type. Must be a Phalcon\Db\Column constant (see below for a list) No
“size” Some type of columns like VARCHAR or INTEGER may have a specific size Yes
“scale” DECIMAL or NUMBER columns may be have a scale to specify how many decimals should be stored Yes
“unsigned” INTEGER columns may be signed or unsigned. This option does not apply to other types of columns Yes
“notNull” Column can store null values? Yes
“autoIncrement” With this attribute column will filled automatically with an auto-increment integer. Only one column in the table can have this attribute. Yes
“first” Column must be placed at first position in the column order Yes
“after” Column must be placed after indicated column Yes

Phalcon\Db supports the following database column types:

  • Phalcon\DbColumn::TYPE_INTEGER
  • Phalcon\DbColumn::TYPE_DATE
  • Phalcon\Db\Column::TYPE_VARCHAR
  • Phalcon\Db\Column::TYPE_DECIMAL
  • Phalcon\Db\Column::TYPE_DATETIME
  • Phalcon\Db\Column::TYPE_CHAR
  • Phalcon\Db\Column::TYPE_TEXT

The associative array passed in Phalcon\Db::createTable() can have the possible keys:

Index Description Optional
“columns” An array with a set of table columns defined with Phalcon\Db\Column No
“indexes” An array with a set of table indexes defined with Phalcon\Db\Index Yes
“references” An array with a set of table references (foreign keys) defined with Phalcon\Db\Reference Yes
“options” An array with a set of table creation options. These options often relate to the database system in which the migration was generated. Yes
Altering Tables

As your application grows, you might need to alter your database, as part of a refactoring or adding new features. Not all database systems allow to modify existing columns or add columns between two existing ones. Phalcon\Db is limited by these constraints.

<?php

use \Phalcon\Db\Column as Column;

// Adding a new column
$connection->addColumn(
    "robots",
    null,
    new Column(
        "robot_type",
        array(
            "type"    => Column::TYPE_VARCHAR,
            "size"    => 32,
            "notNull" => true,
            "after"   => "name",
        )
    )
);

// Modifying an existing column
$connection->modifyColumn(
    "robots",
    null,
    new Column(
        "name",
        array(
            "type" => Column::TYPE_VARCHAR,
            "size" => 40,
            "notNull" => true,
        )
    )
);

// Deleting the column "name"
$connection->deleteColumn("robots", null, "name");
Dropping Tables

Examples on dropping tables:

<?php

// Drop table robot from active database
$connection->dropTable("robots");

//Drop table robot from database "machines"
$connection->dropTable("robots", "machines");

国际化

Phalcon是一个用C语言编写的PHP扩展。这儿有一个 PECL 扩展,为PHP程序提供国际化功能,叫 intl 。我们可以通过PHP官方文档 PHP manual 学习它。

Phalcon原生不支持国际化的功能,因为创建一个这样的组件与PHP intl功能重复。

在下面的例子中,我们将向您展示如何实现使用 intl 扩展为Phalcon应用提供国际化功能。

本指南并不打算完全讲述 intl 扩展的使用。如需要,请访问PHP官方文档: documentation

Find out best available Locale

有几种方式可以找出最佳的可用的语言环境使用 intl 。其中之一就是检查HTTP的 “Accept-Language” 头信息:

<?php

$locale = Locale::acceptFromHttp($_SERVER["HTTP_ACCEPT_LANGUAGE"]);

// Locale could be something like "en_GB" or "en"
echo $locale;

Below method returns a locale identified. It is used to get language, culture, or regionally-specific behavior from the Locale API. Examples of identifiers include:

  • en-US (English, United States)
  • zh-Hant-TW (Chinese, Traditional Script, Taiwan)
  • fr-CA, fr-FR (French for Canada and France respectively)

Formatting messages based on Locale

Part of creating a localized application is to produce concatenated, language-neutral messages. The MessageFormatter allows for the production of those messages.

Printing numbers formatted based on some locale:

<?php

// Prints € 4 560
$formatter = new MessageFormatter("fr_FR", "€ {0, number, integer}");
echo $formatter->format(array(4560));

// Prints USD$ 4,560.5
$formatter = new MessageFormatter("en_US", "USD$ {0, number}");
echo $formatter->format(array(4560.50));

// Prints ARS$ 1.250,25
$formatter = new MessageFormatter("es_AR", "ARS$ {0, number}");
echo $formatter->format(array(1250.25));

Message formatting using time and date patterns:

<?php

//Setting parameters
$time   = time();
$values = array(7, $time, $time);

// Prints "At 3:50:31 PM on Apr 19, 2012, there was a disturbance on planet 7."
$pattern   = "At {1, time} on {1, date}, there was a disturbance on planet {0, number}.";
$formatter = new MessageFormatter("en_US", $pattern);
echo $formatter->format($values);

// Prints "À 15:53:01 le 19 avr. 2012, il y avait une perturbation sur la planète 7."
$pattern   = "À {1, time} le {1, date}, il y avait une perturbation sur la planète {0, number}.";
$formatter = new MessageFormatter("fr_FR", $pattern);
echo $formatter->format($values);

Locale-Sensitive comparison

The Collator class provides string comparison capability with support for appropriate locale-sensitive sort orderings. Check the examples below on the usage of this class:

<?php

// Create a collator using Spanish locale
$collator = new Collator("es");

// Returns that the strings are equal, in spite of the emphasis on the "o"
$collator->setStrength(Collator::PRIMARY);
$collator->compare("una canción", "una cancion");

// Returns that the strings are not equal
$collator->setStrength(Collator::DEFAULT);
$collator->compare("una canción", "una cancion");

数据库迁移

Migrations are a convenient way for you to alter your database in a structured and organized manner.

Important: Migrations are available on Phalcon Developer Tools You need at least Phalcon Framework version 0.5.0 to use developer tools. Also is recommended to have PHP 5.3.11 or greater installed.

Often in development we need to update changes in production environments. Some of these changes could be database modifications like new fields, new tables, removing indexes, etc.

When a migration is generated a set of classes are created to describe how your database is structured at that moment. These classes can be used to synchronize the schema structure on remote databases setting your database ready to work with the new changes that your application implements. Migrations describe these transformations using plain PHP.

Schema Dumping

The Phalcon Developer Tools provides scripts to manage migrations (generation, running and rollback).

The available options for generating migrations are:

_images/migrations-1.png

Running this script without any parameters will simply dump every object (tables and views) from your database in migration classes.

Each migration has a version identifier associated to it. The version number allows us to identify if the migration is newer or older than the current ‘version’ of our database. Versions also inform Phalcon of the running order when executing a migration.

_images/migrations-2.png

When a migration is generated, instructions are displayed on the console to describe the different steps of the migration and the execution time of those statements. At the end, a migration version is generated.

By default Phalcon Developer Tools use the app/migrations directory to dump the migration files. You can change the location by setting one of the parameters on the generation script. Each table in the database has its respective class generated in a separated file under a directory referring its version:

_images/migrations-3.png

Migration Class Anatomy

Each file contains a unique class that extends the Phalcon\Mvc\Model\Migration These classes normally have two methods: up() and down(). Up() performs the migration, while down() rolls it back.

Up() also contains the magic method morphTable(). The magic comes when it recognizes the changes needed to synchronize the actual table in the database to the description given.

<?php

use Phalcon\Db\Column as Column;
use Phalcon\Db\Index as Index;
use Phalcon\Db\Reference as Reference;

class ProductsMigration_100 extends \Phalcon\Mvc\Model\Migration
{

    public function up()
    {
        $this->morphTable(
            "products",
            array(
                "columns" => array(
                    new Column(
                        "id",
                        array(
                            "type"          => Column::TYPE_INTEGER,
                            "size"          => 10,
                            "unsigned"      => true,
                            "notNull"       => true,
                            "autoIncrement" => true,
                            "first"         => true,
                        )
                    ),
                    new Column(
                        "product_types_id",
                        array(
                            "type"     => Column::TYPE_INTEGER,
                            "size"     => 10,
                            "unsigned" => true,
                            "notNull"  => true,
                            "after"    => "id",
                        )
                    ),
                    new Column(
                        "name",
                        array(
                            "type"    => Column::TYPE_VARCHAR,
                            "size"    => 70,
                            "notNull" => true,
                            "after"   => "product_types_id",
                        )
                    ),
                    new Column(
                        "price",
                        array(
                            "type"    => Column::TYPE_DECIMAL,
                            "size"    => 16,
                            "scale"   => 2,
                            "notNull" => true,
                            "after"   => "name",
                        )
                    ),
                ),
                "indexes" => array(
                    new Index(
                        "PRIMARY",
                        array("id")
                    ),
                    new Index(
                        "product_types_id",
                        array("product_types_id")
                    )
                ),
                "references" => array(
                    new Reference(
                        "products_ibfk_1",
                        array(
                            "referencedSchema"  => "invo",
                            "referencedTable"   => "product_types",
                            "columns"           => array("product_types_id"),
                            "referencedColumns" => array("id"),
                        )
                    )
                ),
                "options" => array(
                    "TABLE_TYPE"      => "BASE TABLE",
                    "ENGINE"          => "InnoDB",
                    "TABLE_COLLATION" => "utf8_general_ci",
                )
            )
        );
    }

}

The class is called “ProductsMigration_100”. Suffix 100 refers to the version 1.0.0. morphTable() receives an associative array with 4 possible sections:

Index Description Optional
“columns” An array with a set of table columns No
“indexes” An array with a set of table indexes. Yes
“references” An array with a set of table references (foreign keys). Yes
“options” An array with a set of table creation options. These options are often related to the database system in which the migration was generated. Yes
Defining Columns

Phalcon\Db\Column is used to define table columns. It encapsulates a wide variety of column related features. Its constructor receives as first parameter the column name and an array describing the column. The following options are available when describing columns:

Option Description Optional
“type” Column type. Must be a Phalcon_Db_Column constant (see below) No
“size” Some type of columns like VARCHAR or INTEGER may have a specific size Yes
“scale” DECIMAL or NUMBER columns may be have a scale to specify how much decimals it must store Yes
“unsigned” INTEGER columns may be signed or unsigned. This option does not apply to other types of columns Yes
“notNull” Column can store null values? Yes
“autoIncrement” With this attribute column will filled automatically with an auto-increment integer. Only one column in the table can have this attribute. Yes
“first” Column must be placed at first position in the column order Yes
“after” Column must be placed after indicated column Yes

Database migrations support the following database column types:

  • Phalcon\Db\Column::TYPE_INTEGER
  • Phalcon\Db\Column::TYPE_DATE
  • Phalcon\Db\Column::TYPE_VARCHAR
  • Phalcon\Db\Column::TYPE_DECIMAL
  • Phalcon\Db\Column::TYPE_DATETIME
  • Phalcon\Db\Column::TYPE_CHAR
  • Phalcon\Db\Column::TYPE_TEXT
Defining Indexes

Phalcon\Db\Index defines table indexes. An index only requires that you define a name for it and a list of its columns. Note that if any index has the name PRIMARY, Phalcon will create a primary key index in that table.

Defining References

Phalcon\Db\Reference defines table references (also called foreign keys). The following options can be used to define a reference:

Index Description Optional
“referencedTable” It’s auto-descriptive. It refers to the name of the referenced table. No
“columns” An array with the name of the columns at the table that have the reference No
“referencedColumns” An array with the name of the columns at the referenced table No
“referencedTable” The referenced table maybe is on another schema or database. This option allows you to define that. Yes

Writing Migrations

Migrations aren’t only designed to “morph” table. A migration is just a regular PHP class so you’re not limited to these functions. For example after adding a column you could write code to set the value of that column for existing records. For more details and examples of individual methods, check the database component.

<?php

class ProductsMigration_100 extends \Phalcon\Mvc\Model\Migration
{

    public function up()
    {
        //...
        self::$_connection->insert(
            "products",
            array("Malabar spinach", 14.50),
            array("name", "price")
        );
    }

}

Running Migrations

Once the generated migrations are uploaded on the target server, you can easily run them as shown in the following example:

_images/migrations-4.png
_images/migrations-5.png

Depending on how outdated is the database with respect to migrations, Phalcon may run multiple migration versions in the same migration process. If you specify a target version, Phalcon will run the required migrations until it reaches the specified version.

应用程序调试

PHP offers tools to debug applications with notices, warnings, errors and exceptions. The Exception class offers information such as the file, line, message, numeric code, backtrace etc. on where an error occurred. OOP frameworks like Phalcon mainly use this class to encapsulate this functionality and provide information back to the developer or user.

Despite being written in C, Phalcon runs methods in the PHP userland, providing the debug capability that any other application or framework written in PHP has.

Catching Exceptions

Throughout the tutorials and examples of the Phalcon documentation, there is a common element that is catching exceptions. This is a try/catch block:

<?php

try {

    //... some phalcon code

} catch(\Phalcon\Exception $e) {

}

Any exception thrown within the block is captured in the variable $e. A PhalconException extends the PHP Exception class and is used to understand whether the exception came from Phalcon or PHP itself.

All exceptions generated by PHP are based on the Exception class, and have at least the following elements:

<?php

class Exception
{

    /* Properties */
    protected string $message;
    protected int $code;
    protected string $file;
    protected int $line;

    /* Methods */
    public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]])
    final public string getMessage ( void )
    final public Exception getPrevious ( void )
    final public mixed getCode ( void )
    final public string getFile ( void )
    final public int getLine ( void )
    final public array getTrace ( void )
    final public string getTraceAsString ( void )
    public string __toString ( void )
    final private void __clone ( void )

}

Retrieving information from PhalconException is the same as PHP’s Exception class:

<?php

try {

    //... app code ...

} catch(\Phalcon\Exception $e){
    echo get_class($e), ": ", $e->getMessage(), "\n";
    echo " File=", $e->getFile(), "\n";
    echo " Line=", $e->getLine(), "\n";
    echo $e->getTraceAsString();
}

It’s therefore easy to find which file and line of the application’s code generated the exception, as well as the components involved in generating the exception.

PDOException: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost'
    (using password: NO)
 File=/Applications/MAMP/htdocs/invo/public/index.php
 Line=74
#0 [internal function]: PDO->__construct('mysql:host=loca...', 'root', '', Array)
#1 [internal function]: Phalcon\Db\Adapter\Pdo->connect(Array)
#2 /Applications/MAMP/htdocs/invo/public/index.php(74):
    Phalcon\Db\Adapter\Pdo->__construct(Array)
#3 [internal function]: {closure}()
#4 [internal function]: call_user_func_array(Object(Closure), Array)
#5 [internal function]: Phalcon\DI->_factory(Object(Closure), Array)
#6 [internal function]: Phalcon\DI->get('db', Array)
#7 [internal function]: Phalcon\DI->getShared('db')
#8 [internal function]: Phalcon\Mvc\Model->getConnection()
#9 [internal function]: Phalcon\Mvc\Model::_getOrCreateResultset('Users', Array, true)
#10 /Applications/MAMP/htdocs/invo/app/controllers/SessionController.php(83):
    Phalcon\Mvc\Model::findFirst('email='demo@pha...')
#11 [internal function]: SessionController->startAction()
#12 [internal function]: call_user_func_array(Array, Array)
#13 [internal function]: Phalcon\Mvc\Dispatcher->dispatch()
#14 /Applications/MAMP/htdocs/invo/public/index.php(114): Phalcon\Mvc\Application->handle()
#15 {main}

As you can see from the above output the Phalcon’s classes and methods are displayed just like any other component, and even show the parameters that were invoked in every call. The method Exception::getTrace provides additional information if needed.

Reflection and Instrospection

Any instance of a Phalcon class offers exactly the same behavior than a PHP normal one. It’s possible to use the Reflection API or simply print any object to show how is its internal state:

<?php

$router = new Phalcon\Mvc\Router();
print_r($router);

It’s easy to know the internal state of any object. The above example prints the following:

Phalcon\Mvc\Router Object
(
    [_dependencyInjector:protected] =>
    [_module:protected] =>
    [_controller:protected] =>
    [_action:protected] =>
    [_params:protected] => Array
        (
        )
    [_routes:protected] => Array
        (
            [0] => Phalcon\Mvc\Router\Route Object
                (
                    [_pattern:protected] => #^/([a-zA-Z0-9\_]+)[/]{0,1}$#
                    [_compiledPattern:protected] => #^/([a-zA-Z0-9\_]+)[/]{0,1}$#
                    [_paths:protected] => Array
                        (
                            [controller] => 1
                        )

                    [_methods:protected] =>
                    [_id:protected] => 0
                    [_name:protected] =>
                )

            [1] => Phalcon\Mvc\Router\Route Object
                (
                    [_pattern:protected] => #^/([a-zA-Z0-9\_]+)/([a-zA-Z0-9\_]+)(/.*)*$#
                    [_compiledPattern:protected] => #^/([a-zA-Z0-9\_]+)/([a-zA-Z0-9\_]+)(/.*)*$#
                    [_paths:protected] => Array
                        (
                            [controller] => 1
                            [action] => 2
                            [params] => 3
                        )
                    [_methods:protected] =>
                    [_id:protected] => 1
                    [_name:protected] =>
                )
        )
    [_matchedRoute:protected] =>
    [_matches:protected] =>
    [_wasMatched:protected] =>
    [_defaultModule:protected] =>
    [_defaultController:protected] =>
    [_defaultAction:protected] =>
    [_defaultParams:protected] => Array
        (
        )
)

Using XDebug

XDebug is an amazing tool that complements the debugging of PHP applications. It is also a C extension for PHP, and you can use it together with Phalcon without additional configuration or side effects.

Once you have xdebug installed, you can use its API to get a more detailed information about exceptions and messages. The following example implements xdebug_print_function_stack to stop the execution and generate a backtrace:

<?php

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");

        // Stop execution and show a backtrace
        return xdebug_print_function_stack("stop here!");

        $user        = new Users();
        $user->name  = $name;
        $user->email = $email;

        // Store and check for errors
        $user->save();
    }

}

In this instance, Xdebug will also show us the variables in the local scope, and a backtrace as well:

Xdebug: stop here! in /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php
    on line 19

Call Stack:
    0.0383     654600   1. {main}() /Applications/MAMP/htdocs/tutorial/public/index.php:0
    0.0392     663864   2. Phalcon\Mvc\Application->handle()
        /Applications/MAMP/htdocs/tutorial/public/index.php:37
    0.0418     738848   3. SignupController->registerAction()
        /Applications/MAMP/htdocs/tutorial/public/index.php:0
    0.0419     740144   4. xdebug_print_function_stack()
        /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php:19

Xdebug provides several ways to get debug and trace information regarding the execution of your application using Phalcon. You can check the XDebug documentation for more information.

Phalcon Developer Tools

These tools are a collection of useful scripts to generate skeleton code. Core components of your application can be generated with a simple command, allowing you to easily develop applications using Phalcon.

Important: Phalcon Framework version 0.5.0 or greater is needed to use developer tools. It is highly recommended to use PHP 5.3.6 or greater. If you prefer to use the web version instead of the console, this blog post offers more information.

Download

You can download or clone a cross platform package containing the developer tools from Github.

Installation

These are detailed instructions on how to install the developer tools on different platforms:

Phalcon Developer Tools on Windows

These steps will guide you through the process of installing Phalcon Developer Tools for Windows.

Prerequisites

The Phalcon PHP extension is required to run Phalcon Tools. If you haven’t installed it yet, please see the Installation section for instructions.

Download

You can download a cross platform package containing the developer tools from the Download section. Also you can clone it from Github.

On the Windows platform, you need to configure the system PATH to include Phalcon tools as well as the PHP executable. If you download the Phalcon tools as a zip archive, extract it on any path of your local drive i.e. c:\phalcon-tools. You will need this path in the steps below. Edit the file “phalcon.bat” by right clicking on the file and selecting “Edit”:

_images/path-0.png

Change the path to the one you installed the Phalcon tools:

_images/path-01.png

Save the changes.

Adding PHP and Tools to your system PATH

Because the scripts are written in PHP, you need to install it on your machine. Depending on your PHP installation, the executable can be located in various places. Search for the file php.exe and copy the path it is located in. For instance, if using the latest WAMP stack, PHP is located in: C:\wampbin\php\php5.3.10\php.exe.

From the Windows start menu, right mouse click on the “My Computer” icon and select “Properties”:

_images/path-1.png

Click the “Advanced” tab and then the button “Environment Variables”:

_images/path-2.png

At the bottom, look for the section “System variables” and edit the variable “Path”:

_images/path-3.png

Be very careful on this step! You need to append at the end of the long string the path where your php.exe was located and the path where Phalcon tools are installed. Use the ”;” character to separate the differents paths in the variable:

_images/path-4.png

Accept the changes made by clicking “OK” and close the dialogs opened. From the start menu click on the option “Run”. If you can’t find this option, press “Windows Key” + “R”.

_images/path-5.png

Type “cmd” and press enter to open the windows command line utility:

_images/path-6.png

Type the commands “php -v” and “phalcon” and you will see something like this:

_images/path-7.png

Congratulations you now have Phalcon tools installed!

Phalcon Developer Tools on Mac OS X

These steps will guide you through the process of installing Phalcon Developer Tools for OS/X.

Prerequisites

The Phalcon PHP extension is required to run Phalcon Tools. If you haven’t installed it yet, please see the Installation section for instructions.

Download

You can download a cross platform package containing the developer tools from the Download section. You can also clone it from Github.

Open the terminal application:

_images/mac-1.png

Copy & Paste the commands below in your terminal:

wget -q --no-check-certificate -O phalcon-tools.zip http://github.com/phalcon/phalcon-devtools/zipball/master
unzip -q phalcon-tools.zip
mv phalcon-phalcon-devtools-* phalcon-tools

Check where the phalcon-tools directory was installed using a pwd command in your terminal:

_images/mac-2.png

On the Mac platform, you need to configure your user PATH to include Phalcon tools. Edit your .profile and append the Phalcon tools path to the environment variable PATH:

_images/mac-3.png

Insert these two lines at the end of the file:

export PATH=$PATH:/Users/scott/phalcon-tools
export PTOOLSPATH=/Users/scott/phalcon-tools

The .profile should look like this:

_images/mac-4.png

Save your changes and close the editor. In the terminal window, type the following commands to create a symbolic link to the phalcon.sh script:

ln -s ~/phalcon-tools/phalcon.sh ~/phalcon-tools/phalcon
chmod +x ~/phalcon-tools/phalcon

Type the command “phalcon” and you will see something like this:

_images/mac-5.png

Congratulations you now have Phalcon tools installed!

Phalcon Developer Tools on Linux

These steps will guide you through the process of installing Phalcon Developer Tools for Linux.

Prerequisites

The Phalcon PHP extension is required to run Phalcon Tools. If you haven’t installed it yet, please see the Installation section for instructions.

Download

You can download a cross platform package containing the developer tools from the Download section. Also you can clone it from Github.

Open a terminal and type the commands below:

_images/linux-1.png

Then enter the folder where the tools were cloned and execute ”. ./phalcon.sh”, (don’t forget the dot at beginning of the command):

_images/linux-2.png

Congratulations you now have Phalcon tools installed!

Getting Available Commands

You can get a list of available commands in Phalcon tools by typing: phalcon commands

_images/tools-4.png

Generating a Project Skeleton

You can use Phalcon tools to generate pre-defined project skeletons for your applications with Phalcon framework. By default the project skeleton generator will use mod_rewrite for Apache. Type the following command on your web server document root:

_images/tools-1.png

The above recommended project structure was generated:

_images/tools-2.png

You could add the parameter –help to get help on the usage of a certain script:

_images/tools-3.png

Accessing the project from the web server will show you:

_images/tools-6.png

Generating Controllers

The command “create-controller” generates controller skeleton structures. It’s important to invoke this command inside a directory that already has a Phalcon project.

_images/tools-5.png

The following code is generated by the script:

<?php

class TestController extends Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

}

Preparing Database Settings

When a project is generated using developer tools. A configuration file can be found in app/config/config.ini To generate models or scaffold, you will need to change the settings used to connect to your database.

Change the database section in your config.ini file:

[database]
adapter  = Mysql
host     = "127.0.0.1"
username = "root"
password = "secret"
name     = "store_db"

[phalcon]
controllersDir = "../app/controllers/"
modelsDir      = "../app/models/"
viewsDir       = "../app/views/"
baseUri        = "/store/"

Generating Models

There are several ways to create models. You can create all models from the default database connection or some selectively. Models can have public attributes for the field representations or setters/getters can be used. The simplest way to generate a model is:

_images/tools-7.png

All table fields are declared public for direct access.

<?php

class Products extends \Phalcon\Mvc\Model
{

    /**
     * @var integer
     */
    public $id;

    /**
     * @var integer
     */
    public $types_id;

    /**
     * @var string
     */
    public $name;

    /**
     * @var string
     */
    public $price;

    /**
     * @var integer
     */
    public $quantity;

    /**
     * @var string
     */
    public $status;

}

By adding the –get-set you can generate the fields with protected variables and public setter/getter methods. Those methods can help in business logic implementation within the setter/getter methods.

<?php

class Products extends \Phalcon\Mvc\Model
{

    /**
     * @var integer
     */
    protected $id;

    /**
     * @var integer
     */
    protected $types_id;

    /**
     * @var string
     */
    protected $name;

    /**
     * @var string
     */
    protected $price;

    /**
     * @var integer
     */
    protected $quantity;

    /**
     * @var string
     */
    protected $status;


    /**
     * Method to set the value of field id
     * @param integer $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Method to set the value of field types_id
     * @param integer $types_id
     */
    public function setTypesId($types_id)
    {
        $this->types_id = $types_id;
    }

    ...

    /**
     * Returns the value of field status
     * @return string
     */
    public function getStatus()
    {
        return $this->status;
    }

}

A nice feature of the model generator is that it keeps changes made by the developer between code generations. This allows the addition or removal of fields and properties, without worrying about losing changes made to the model itself. The following screencast shows you how it works:

Scaffold a CRUD

Scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.

Once the code is generated, it will have to be customized to meet your needs. Many developers avoid scaffolding entirely, opting to write all or most of their source code from scratch. The generated code can serve as a guide to better understand of how the framework works or develop prototypes. The screenshot below shows a scaffold based on the table “products”:

_images/tools-9.png

The scaffold generator will build several files in your application, along with some folders. Here’s a quick overview of what will be generated:

File Purpose
app/controllers/ProductsController.php The Products controller
app/models/Products.php The Products model
app/views/layout/products.phtml Controller layout for Products
app/views/products/new.phtml View for the action “new”
app/views/products/edit.phtml View for the action “edit”
app/views/products/search.phtml View for the action “search”
app/views/products/edit.phtml View for the action “edit”

When browsing the recently generated controller, you will see a search form and a link to create a new Product:

_images/tools-10.png

The “create page” allows you to create products applying validations on the Products model. Phalcon will automatically validate not null fields producing warnings if any of them is required.

_images/tools-11.png

After performing a search, a pager component is available to show paged results. Use the “Edit” or “Delete” links in front of each result to perform such actions.

_images/tools-12.png

Web Interface to Tools

Also, if you prefer, it’s possible to use Phalcon Developer Tools from a web interface. Check out the following screencast to figure out how it works:

Integrating Tools with PhpStorm IDE

The screencast below shows how to integrate developer tools with the PhpStorm IDE. The configuration steps could be easily adapted to other IDEs for PHP.

Conclusion

Phalcon Developer Tools provides an easy way to generate code for your application, reducing development time and potential coding errors.

API Indice

Class Phalcon\Acl

implements Phalcon\Events\EventsAwareInterface

This component allows to manage ACL lists. An access control list (ACL) is a list of permissions attached to an object. An ACL specifies which users or system processes are granted access to objects, as well as what operations are allowed on given objects.

<?php

$acl = new Phalcon\Acl\Adapter\Memory();

//Default action is deny access
$acl->setDefaultAction(Phalcon\Acl::DENY);

//Create some roles
$roleAdmins = new Phalcon\Acl\Role('Administrators', 'Super-User role');
$roleGuests = new Phalcon\Acl\Role('Guests');

//Add "Guests" role to acl
$acl->addRole($roleGuests);

//Add "Designers" role to acl
$acl->addRole('Designers'));

//Define the "Customers" resource
$customersResource = new Phalcon\Acl\Resource('Customers', 'Customers management');

//Add "customers" resource with a couple of operations
$acl->addResource($customersResource, 'search');
$acl->addResource($customersResource, array('create', 'update'));

//Set access level for roles into resources
$acl->allow('Guests', 'Customers', 'search');
$acl->allow('Guests', 'Customers', 'create');
$acl->deny('Guests', 'Customers', 'update');

//Check whether role has access to the operations
$acl->isAllowed('Guests', 'Customers', 'edit') //Returns 0
$acl->isAllowed('Guests', 'Customers', 'search'); //Returns 1
$acl->isAllowed('Guests', 'Customers', 'create'); //Returns 1
Constants

integer ALLOW

integer DENY

Methods

public setEventsManager (unknown $eventsManager)

Sets the events manager

public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

Class Phalcon\Acl\Adapter\Memory

extends Phalcon\Acl

implements Phalcon\Events\EventsAwareInterface, Phalcon\Acl\AdapterInterface

Manages ACL lists in memory

<?php

$acl = new Phalcon\Acl\Adapter\Memory();

$acl->setDefaultAction(Phalcon\Acl::DENY);

//Register roles
$roles = array(
    'users' => new Phalcon\Acl\Role('Users'),
    'guests' => new Phalcon\Acl\Role('Guests')
);
foreach($roles as $role){
    $acl->addRole($role);
}

//Private area resources
  $privateResources = array(
    'companies' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'),
    'products' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'),
    'invoices' => array('index', 'profile')
);
foreach($privateResources as $resource => $actions){
    $acl->addResource(new Phalcon\Acl\Resource($resource), $actions);
}

//Private area resources
$publicResources = array(
    'index' => array('index'),
    'about' => array('index'),
    'session' => array('index', 'register', 'start', 'end'),
    'contact' => array('index', 'send')
);
  foreach($publicResources as $resource => $actions){
    $acl->addResource(new Phalcon\Acl\Resource($resource), $actions);
}

  //Grant access to public areas to both users and guests
foreach($roles as $role){
    foreach($publicResources as $resource => $actions){
            $acl->allow($role->getName(), $resource, '*');
    }
}

//Grant acess to private area to role Users
  foreach($privateResources as $resource => $actions){
            foreach($actions as $action){
            $acl->allow('Users', $resource, $action);
    }
}
Constants

integer ALLOW

integer DENY

Methods

public __construct ()

Phalcon\Acl\Adapter\Memory constructor

public setDefaultAction (int $defaultAccess)

Sets the default access level (Phalcon\Acl::ALLOW or Phalcon\Acl::DENY)

public int getDefaultAction ()

Returns the default ACL access level

public boolean addRole (Phalcon\Acl\RoleInterface $roleObject, array $accessInherits)

Adds a role to the ACL list. Second parameter lets to inherit access data from other existing role Example:

<?php

 $acl->addRole(new Phalcon\Acl\Role('administrator'), 'consultant');
 $acl->addRole('administrator', 'consultant');

public addInherit (string $roleName, string $roleToInherit)

Do a role inherit from another existing role

public boolean isRole (string $roleName)

Check whether role exist in the roles list

public boolean isResource (string $resourceName)

Check whether resource exist in the resources list

public boolean addResource (Phalcon\Acl\Resource $resource, unknown $accessList)

Adds a resource to the ACL list Access names can be a particular action, by example search, update, delete, etc or a list of them Example:

<?php

 //Add a resource to the the list allowing access to an action
 $acl->addResource(new Phalcon\Acl\Resource('customers'), 'search');
 $acl->addResource('customers', 'search');

 //Add a resource  with an access list
 $acl->addResource(new Phalcon\Acl\Resource('customers'), array('create', 'search'));
 $acl->addResource('customers', array('create', 'search'));

public addResourceAccess (string $resourceName, mixed $accessList)

Adds access to resources

public dropResourceAccess (string $resourceName, mixed $accessList)

Removes an access from a resource

protected _allowOrDeny ()

Checks if a role has access to a resource

public allow (string $roleName, string $resourceName, mixed $access)

Allow access to a role on a resource You can use ‘*’ as wildcard Example:

<?php

 //Allow access to guests to search on customers
 $acl->allow('guests', 'customers', 'search');

 //Allow access to guests to search or create on customers
 $acl->allow('guests', 'customers', array('search', 'create'));

 //Allow access to any role to browse on products
 $acl->allow('*', 'products', 'browse');

 //Allow access to any role to browse on any resource
 $acl->allow('*', '*', 'browse');

public boolean deny (string $roleName, string $resourceName, mixed $access)

Deny access to a role on a resource You can use ‘*’ as wildcard Example:

<?php

 //Deny access to guests to search on customers
 $acl->deny('guests', 'customers', 'search');

 //Deny access to guests to search or create on customers
 $acl->deny('guests', 'customers', array('search', 'create'));

 //Deny access to any role to browse on products
 $acl->deny('*', 'products', 'browse');

 //Deny access to any role to browse on any resource
 $acl->deny('*', '*', 'browse');

public boolean isAllowed (string $role, string $resource, unknown $access)

Check whether a role is allowed to access an action from a resource

<?php

 //Does andres have access to the customers resource to create?
 $acl->isAllowed('andres', 'Products', 'create');

 //Do guests have access to any resource to edit?
 $acl->isAllowed('guests', '*', 'edit');

public string getActiveRole ()

Returns the role which the list is checking if it’s allowed to certain resource/access

public string getActiveResource ()

Returns the resource which the list is checking if some role can access it

public string getActiveAccess ()

Returns the access which the list is checking if some role can access it

protected _rebuildAccessList ()

Rebuild the list of access from the inherit lists

public setEventsManager (unknown $eventsManager) inherited from Phalcon\Acl

Sets the events manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\Acl

Returns the internal event manager

Class Phalcon\Acl\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Acl\Resource

implements Phalcon\Acl\ResourceInterface

This class defines resource entity and its description

Methods

public __construct (string $name, string $description)

Phalcon\Acl\Resource constructor

public string getName ()

Returns the resource name

public string getDescription ()

Returns resource description

public string __toString ()

Magic method __toString

Class Phalcon\Acl\Role

implements Phalcon\Acl\RoleInterface

This class defines role entity and its description

Methods

public __construct (string $name, string $description)

Phalcon\Acl\Role description

public string getName ()

Returns the role name

public string getDescription ()

Returns role description

public string __toString ()

Magic method __toString

Class Phalcon\CLI\Console

implements Phalcon\DI\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

This component allows to create CLI applications using Phalcon

Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the events manager

public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

public registerModules (array $modules)

Register an array of modules present in the console

<?php

$this->registerModules(array(
    'frontend' => array(
            'className' => 'Multiple\Frontend\Module',
            'path' => '../apps/frontend/Module.php'
    ),
    'backend' => array(
            'className' => 'Multiple\Backend\Module',
            'path' => '../apps/backend/Module.php'
    )
));

public addModules (array $modules)

Merge modules with the existing ones

public array getModules ()

Return the modules registered in the console

public mixed handle (array $arguments)

Handle the whole command-line tasks

Class Phalcon\CLI\Console\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\CLI\Dispatcher

extends Phalcon\Dispatcher

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface, Phalcon\DispatcherInterface

Dispatching is the process of taking the command-line arguments, extracting the module name, task name, action name, and optional parameters contained in it, and then instantiating a task and calling an action on it.

<?php

$di = new Phalcon\DI();

$dispatcher = new Phalcon\CLI\Dispatcher();

  $dispatcher->setDI($di);

$dispatcher->setTaskName('posts');
$dispatcher->setActionName('index');
$dispatcher->setParams(array());

$handle = $dispatcher->dispatch();
Constants

integer EXCEPTION_NO_DI

integer EXCEPTION_CYCLIC_ROUTING

integer EXCEPTION_HANDLER_NOT_FOUND

integer EXCEPTION_INVALID_HANDLER

integer EXCEPTION_INVALID_PARAMS

integer EXCEPTION_ACTION_NOT_FOUND

Methods

public setTaskSuffix (string $taskSuffix)

Sets the default task suffix

public setDefaultTask (string $taskName)

Sets the default task name

public setTaskName (string $taskName)

Sets the task name to be dispatched

public string getTaskName ()

Gets last dispatched task name

protected _throwDispatchException ()

Throws an internal exception

public Phalcon\CLI\Task getLastTask ()

Returns the lastest dispatched controller

public Phalcon\CLI\Task getActiveTask ()

Returns the active task in the dispatcher

public __construct () inherited from Phalcon\Dispatcher

Phalcon\Dispatcher constructor

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Dispatcher

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\Dispatcher

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Dispatcher

Sets the events manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\Dispatcher

Returns the internal event manager

public setActionSuffix (string $actionSuffix) inherited from Phalcon\Dispatcher

Sets the default action suffix

public setNamespaceName (string $namespaceName) inherited from Phalcon\Dispatcher

Sets a namespace to be prepended to the handler name

public string getNamespaceName () inherited from Phalcon\Dispatcher

Gets a namespace to be prepended to the current handler name

public setDefaultNamespace (string $namespace) inherited from Phalcon\Dispatcher

Sets the default namespace

public string getDefaultNamespace () inherited from Phalcon\Dispatcher

Returns the default namespace

public setDefaultAction (string $actionName) inherited from Phalcon\Dispatcher

Sets the default action name

public setActionName (string $actionName) inherited from Phalcon\Dispatcher

Sets the action name to be dispatched

public string getActionName () inherited from Phalcon\Dispatcher

Gets last dispatched action name

public setParams (array $params) inherited from Phalcon\Dispatcher

Sets action params to be dispatched

public array getParams () inherited from Phalcon\Dispatcher

Gets action params

public setParam (mixed $param, mixed $value) inherited from Phalcon\Dispatcher

Set a param by its name or numeric index

public mixed getParam (mixed $param, string|array $filters, mixed $defaultValue) inherited from Phalcon\Dispatcher

Gets a param by its name or numeric index

public boolean isFinished () inherited from Phalcon\Dispatcher

Checks if the dispatch loop is finished or has more pendent controllers/tasks to disptach

public mixed getReturnedValue () inherited from Phalcon\Dispatcher

Returns value returned by the lastest dispatched action

public object dispatch () inherited from Phalcon\Dispatcher

Dispatches a handle action taking into account the routing parameters

public forward (array $forward) inherited from Phalcon\Dispatcher

Forwards the execution flow to another controller/action

Class Phalcon\CLI\Dispatcher\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\CLI\Router

implements Phalcon\DI\InjectionAwareInterface

Phalcon\CLI\Router is the standard framework router. Routing is the process of taking a command-line arguments and decomposing it into parameters to determine which module, task, and action of that task should receive the request

<?php

$router = new Phalcon\CLI\Router();
$router->handle(array());
echo $router->getTaskName();
Methods

public __construct ()

Phalcon\CLI\Router constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

public setDefaultModule (string $moduleName)

Sets the name of the default module

public setDefaultTask (unknown $taskName)

Sets the default controller name

public setDefaultAction (string $actionName)

Sets the default action name

public handle (array $arguments)

Handles routing information received from command-line arguments

public string getModuleName ()

Returns proccesed module name

public string getTaskName ()

Returns proccesed task name

public string getActionName ()

Returns proccesed action name

public array getParams ()

Returns proccesed extra params

Class Phalcon\CLI\Router\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\CLI\Task

extends Phalcon\DI\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface

Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run “tasks” such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a “runAction” method

<?php

class HelloTask extends \Phalcon\CLI\Task
{

  //This action will be executed by default
  public function runAction()
  {

  }

  public function findAction()
  {

  }

  //This action will be executed when a non existent action is requested
  public function notFoundAction()
  {

  }

}
Methods

final public __construct ()

Phalcon\CLI\Task constructor

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI\Injectable

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Cache\Backend

This class implements common functionality for backend adapters. All the backend cache adapter must extend this class

Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, array $options)

Phalcon\Cache\Backend constructor

public mixed start (int|string $keyName)

Starts a cache. The $keyname allows to identify the created fragment

public stop (boolean $stopBuffer)

Stops the frontend without store any cached content

public mixed getFrontend ()

Returns front-end instance adapter related to the back-end

public array getOptions ()

Returns the backend options

public boolean isFresh ()

Checks whether the last cache is fresh or cached

public boolean isStarted ()

Checks whether the cache has starting buffering or not

public setLastKey (string $lastKey)

Sets the last key used in the cache

public string getLastKey ()

Gets the last key stored by the cache

Class Phalcon\Cache\Backend\Apc

extends Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Allows to cache output fragments, PHP data and raw data using a memcache backend

<?php

//Cache data for 2 days
$frontendOptions = array(
    'lifetime' => 172800
);

//Cache data for 2 days
$frontCache = new Phalcon\Cache\Frontend\Data(array(
    'lifetime' => 172800
));

  $cache = new Phalcon\Cache\Backend\Apc($frontCache);

//Cache arbitrary data
$cache->store('my-data', array(1, 2, 3, 4, 5));

//Get data
$data = $cache->get('my-data');
Methods

public mixed get (string $keyName, long $lifetime)

Returns a cached content

public save (string $keyName, string $content, long $lifetime, boolean $stopBuffer)

Stores cached content into the APC backend and stops the frontend

public boolean delete (string $keyName)

Deletes a value from the cache by its key

public array queryKeys (string $prefix)

Query the existing cached keys

public boolean exists (string $keyName, long $lifetime)

Checks if cache exists and it hasn’t expired

public __construct (Phalcon\Cache\FrontendInterface $frontend, array $options) inherited from Phalcon\Cache\Backend

Phalcon\Cache\Backend constructor

public mixed start (int|string $keyName) inherited from Phalcon\Cache\Backend

Starts a cache. The $keyname allows to identify the created fragment

public stop (boolean $stopBuffer) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public mixed getFrontend () inherited from Phalcon\Cache\Backend

Returns front-end instance adapter related to the back-end

public array getOptions () inherited from Phalcon\Cache\Backend

Returns the backend options

public boolean isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public boolean isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public setLastKey (string $lastKey) inherited from Phalcon\Cache\Backend

Sets the last key used in the cache

public string getLastKey () inherited from Phalcon\Cache\Backend

Gets the last key stored by the cache

Class Phalcon\Cache\Backend\File

extends Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Allows to cache output fragments using a file backend

<?php

//Cache the file for 2 days
$frontendOptions = array(
    'lifetime' => 172800
);

//Set the cache directory
$backendOptions = array(
    'cacheDir' => '../app/cache/'
);

$cache = Phalcon_Cache::factory('Output', 'File', $frontendOptions, $backendOptions);

$content = $cache->start('my-cache');
if($content===null){
    echo '<h1>', time(), '</h1>';
    $cache->save();
} else {
    echo $content;
}
Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, array $options)

Phalcon\Cache\Backend\File constructor

public mixed get (int|string $keyName, long $lifetime)

Returns a cached content

public save (int|string $keyName, string $content, long $lifetime, boolean $stopBuffer)

Stores cached content into the file backend and stops the frontend

public boolean delete (int|string $keyName)

Deletes a value from the cache by its key

public array queryKeys (string $prefix)

Query the existing cached keys

public boolean exists (string $keyName, long $lifetime)

Checks if cache exists and it isn’t expired

public mixed start (int|string $keyName) inherited from Phalcon\Cache\Backend

Starts a cache. The $keyname allows to identify the created fragment

public stop (boolean $stopBuffer) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public mixed getFrontend () inherited from Phalcon\Cache\Backend

Returns front-end instance adapter related to the back-end

public array getOptions () inherited from Phalcon\Cache\Backend

Returns the backend options

public boolean isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public boolean isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public setLastKey (string $lastKey) inherited from Phalcon\Cache\Backend

Sets the last key used in the cache

public string getLastKey () inherited from Phalcon\Cache\Backend

Gets the last key stored by the cache

Class Phalcon\Cache\Backend\Memcache

extends Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Allows to cache output fragments, PHP data or raw data to a memcache backend This adapter uses the special memcached key “_PHCM” to store all the keys internally used by the adapter

<?php

 // Cache data for 2 days
 $frontCache = new Phalcon\Cache\Frontend\Data(array(
    "lifetime" => 172800
 ));

 //Create the Cache setting memcached connection options
 $cache = new Phalcon\Cache\Backend\File($frontCache, array(
    'host' => 'localhost',
    'port' => 11211,
    'persistent' => false
 ));

 //Cache arbitrary data
 $cache->store('my-data', array(1, 2, 3, 4, 5));

 //Get data
 $data = $cache->get('my-data');
Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, array $options)

Phalcon\Cache\Backend\Memcache constructor

protected _connect ()

Create internal connection to memcached

public mixed get (int|string $keyName, long $lifetime)

Returns a cached content

public save (int|string $keyName, string $content, long $lifetime, boolean $stopBuffer)

Stores cached content into the Memcached backend and stops the frontend

public boolean delete (int|string $keyName)

Deletes a value from the cache by its key

public array queryKeys (string $prefix)

Query the existing cached keys

public boolean exists (string $keyName, long $lifetime)

Checks if cache exists and it hasn’t expired

public __destruct ()

Destructs the backend closing the memcached connection

public mixed start (int|string $keyName) inherited from Phalcon\Cache\Backend

Starts a cache. The $keyname allows to identify the created fragment

public stop (boolean $stopBuffer) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public mixed getFrontend () inherited from Phalcon\Cache\Backend

Returns front-end instance adapter related to the back-end

public array getOptions () inherited from Phalcon\Cache\Backend

Returns the backend options

public boolean isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public boolean isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public setLastKey (string $lastKey) inherited from Phalcon\Cache\Backend

Sets the last key used in the cache

public string getLastKey () inherited from Phalcon\Cache\Backend

Gets the last key stored by the cache

Class Phalcon\Cache\Backend\Mongo

extends Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Allows to cache output fragments, PHP data or raw data to a MongoDb backend

<?php

 // Cache data for 2 days
 $frontCache = new Phalcon\Cache\Frontend\Base64(array(
    "lifetime" => 172800
 ));

 //Create a MongoDB cache
 $cache = new Phalcon\Cache\Backend\Mongo($frontCache, array(
    'server' => "mongodb://localhost",
      'db' => 'caches',
    'collection' => 'images'
 ));

 //Cache arbitrary data
 $cache->store('my-data', file_get_contents('some-image.jpg'));

 //Get data
 $data = $cache->get('my-data');
Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, array $options)

Phalcon\Cache\Backend\Mongo constructor

protected MongoCollection _getCollection ()

Returns a MongoDb collection based on the backend parameters

public mixed get (int|string $keyName, long $lifetime)

Returns a cached content

public save (int|string $keyName, string $content, long $lifetime, boolean $stopBuffer)

Stores cached content into the Mongo backend and stops the frontend

public boolean delete (int|string $keyName)

Deletes a value from the cache by its key

public array queryKeys (string $prefix)

Query the existing cached keys

public boolean exists (string $keyName, long $lifetime)

Checks if cache exists and it hasn’t expired

public mixed start (int|string $keyName) inherited from Phalcon\Cache\Backend

Starts a cache. The $keyname allows to identify the created fragment

public stop (boolean $stopBuffer) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public mixed getFrontend () inherited from Phalcon\Cache\Backend

Returns front-end instance adapter related to the back-end

public array getOptions () inherited from Phalcon\Cache\Backend

Returns the backend options

public boolean isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public boolean isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public setLastKey (string $lastKey) inherited from Phalcon\Cache\Backend

Sets the last key used in the cache

public string getLastKey () inherited from Phalcon\Cache\Backend

Gets the last key stored by the cache

Class Phalcon\Cache\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Cache\Frontend\Base64

implements Phalcon\Cache\FrontendInterface

Methods

public __construct (unknown $frontendOptions)

...

public getLifetime ()

...

public isBuffering ()

...

public start ()

...

public getContent ()

...

public stop ()

...

public beforeStore (unknown $data)

...

public afterRetrieve (unknown $data)

...

Class Phalcon\Cache\Frontend\Data

implements Phalcon\Cache\FrontendInterface

Allows to cache native PHP data in a serialized form

<?php

 // Cache the files for 2 days using a Data frontend
 $frontCache = new Phalcon\Cache\Frontend\Data(array(
    "lifetime" => 172800
 ));

 // Create the component that will cache "Data" to a "File" backend
 // Set the cache file directory - important to keep the "/" at the end of
 // of the value for the folder
 $cache = new Phalcon\Cache\Backend\File($frontCache, array(
     "cacheDir" => "../app/cache/"
 ));

 // Try to get cached records
 $cacheKey = 'robots_order_id.cache';
 $robots    = $cache->get($cacheKey);
 if ($robots === null) {

     // $robots is null due to cache expiration or data does not exist
     // Make the database call and populate the variable
     $robots = Robots::find(array("order" => "id"));

     // Store it in the cache
     $cache->save($cacheKey, $robots);
 }

 // Use $robots :)
 foreach ($robots as $robot) {
    echo $robot->name, "\n";
 }
Methods

public __construct (array $frontendOptions)

Phalcon\Cache\Frontend\Data constructor

public int getLifetime ()

Returns cache lifetime

public boolean isBuffering ()

Check whether if frontend is buffering output

public start ()

Starts output frontend. Actually, does nothing

public string getContent ()

Returns output cached content

public stop ()

Stops output frontend

public beforeStore (mixed $data)

Serializes data before storing it

public afterRetrieve (mixed $data)

Unserializes data after retrieving it

Class Phalcon\Cache\Frontend\None

implements Phalcon\Cache\FrontendInterface

Discards any kind of frontend data input. This frontend does not have expiration time or any other options

<?php

 //Create a None Cache
 $frontCache = new Phalcon\Cache\Frontend\None();

 // Create the component that will cache "Data" to a "Memcached" backend
 // Memcached connection settings
 $cache = new Phalcon\Cache\Backend\Memcached($frontCache, array(
     "host" => "localhost",
     "port" => "11211"
 ));

 // This Frontend always return the data as it's returned by the backend
 $cacheKey = 'robots_order_id.cache';
 $robots    = $cache->get($cacheKey);
 if ($robots === null) {

     // This cache doesn't perform any expiration checking, so the data is always expired
     // Make the database call and populate the variable
     $robots = Robots::find(array("order" => "id"));

     $cache->save($cacheKey, $robots);
 }

 // Use $robots :)
 foreach ($robots as $robot) {
    echo $robot->name, "\n";
 }
Methods

public __construct (unknown $frontendOptions)

Phalcon\Cache\Frontend\None constructor

public int getLifetime ()

Returns cache lifetime, always one second expiring content

public boolean isBuffering ()

Check whether if frontend is buffering output, always false

public start ()

Starts output frontend

public string getContent ()

Returns output cached content

public stop ()

Stops output frontend

public beforeStore (mixed $data)

Prepare data to be stored

public afterRetrieve (mixed $data)

Prepares data to be retrieved to user

Class Phalcon\Cache\Frontend\Output

implements Phalcon\Cache\FrontendInterface

Allows to cache output fragments captured with ob_* functions

<?php

 //Create an Output frontend. Cache the files for 2 days
 $frontCache = new Phalcon\Cache\Frontend\Output(array(
   "lifetime" => 172800
 ));

 // Create the component that will cache from the "Output" to a "File" backend
 // Set the cache file directory - it's important to keep the "/" at the end of
 // the value for the folder
 $cache = new Phalcon\Cache\Backend\File($frontCache, array(
     "cacheDir" => "../app/cache/"
 ));

 // Get/Set the cache file to ../app/cache/my-cache.html
 $content = $cache->start("my-cache.html");

 // If $content is null then the content will be generated for the cache
 if ($content === null) {

     //Print date and time
     echo date("r");

     //Generate a link to the sign-up action
     echo Phalcon\Tag::linkTo(
         array(
             "user/signup",
             "Sign Up",
             "class" => "signup-button"
         )
     );

     // Store the output into the cache file
     $cache->save();

 } else {

     // Echo the cached output
     echo $content;
 }
Methods

public __construct (array $frontendOptions)

Phalcon\Cache\Frontend\Output constructor

public integer getLifetime ()

Returns cache lifetime

public boolean isBuffering ()

Check whether if frontend is buffering output

public start ()

Starts output frontend

public string getContent ()

Returns output cached content

public stop ()

Stops output frontend

public beforeStore (mixed $data)

Prepare data to be stored

public afterRetrieve (mixed $data)

Prepares data to be retrieved to user

Class Phalcon\Config

Phalcon\Config is designed to simplify the access to, and the use of, configuration data within applications. It provides a nested object property based user interface for accessing this configuration data within application code.

<?php

 $config = new Phalcon\Config(array(
  "database" => array(
    "adapter" => "Mysql",
    "host" => "localhost",
    "username" => "scott",
    "password" => "cheetah",
    "name" => "test_db"
  ),
  "phalcon" => array(
    "controllersDir" => "../app/controllers/",
    "modelsDir" => "../app/models/",
    "viewsDir" => "../app/views/"
  )

));

Methods

public __construct (array $arrayConfig)

Phalcon\Config constructor

public static Phalcon\Config __set_state (unknown $data)

Restores the state of a Phalcon\Config object

Class Phalcon\Config\Adapter\Ini

extends Phalcon\Config

Reads ini files and convert it to Phalcon\Config objects. Given the next configuration file:

  <?php

  [database]
  adapter = Mysql
  host = localhost
  username = scott
  password = cheetah
  name = test_db

  [phalcon]
  controllersDir = "../app/controllers/"
  modelsDir = "../app/models/"
  viewsDir = "../app/views/"

You can read it as follows:
<?php

$config = new Phalcon\Config\Adapter\Ini("path/config.ini");
echo $config->phalcon->controllersDir;
echo $config->database->username;
Methods

public __construct (string $filePath)

Phalcon\Config\Adapter\Ini constructor

public static Phalcon\Config __set_state (unknown $data) inherited from Phalcon\Config

Restores the state of a Phalcon\Config object

Class Phalcon\Config\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\DI

implements Phalcon\DiInterface

Phalcon\DI is a component that implements Dependency Injection of services and it’s itself a container for them. Since Phalcon is highly decoupled, Phalcon\DI is essential to integrate the different components of the framework. The developer can also use this component to inject dependencies and manage global instances of the different classes used in the application. Basically, this component implements the Inversion of Control pattern. Applying this, the objects do not receive their dependencies using setters or constructors, but requesting a service dependency injector. This reduces the overall complexity, since there is only one way to get the required dependencies within a component. Additionally, this pattern increases testability in the code, thus making it less prone to errors.

Methods

public __construct ()

Phalcon\DI constructor

public Phalcon\Di\ServiceInterface set (string $name, mixed $config, boolean $shared)

Registers a service in the services container

public Phalcon\Di\ServiceInterface setShared (string $name, mixed $config)

Registers an “always shared” service in the services container

public remove (string $name)

Removes a service in the services container

public Phalcon\Di\ServiceInterface attempt (string $name, mixed $config, unknown $shared)

Attempts to register a service in the services container Only is successful if a service hasn’t been registered previously with the same name

public mixed getRaw (string $name)

Returns a service definition without resolving

public Phalcon\Di\ServiceInterface getService (unknown $name)

Returns a Phalcon\Di\Service instance

public mixed get (string $name, array $parameters)

Resolves the service based on its configuration

public mixed getShared (string $name, array $parameters)

Returns a shared service based on their configuration

public boolean has (string $name)

Check whether the DI contains a service by a name

public boolean wasFreshInstance ()

Check whether the last service obtained via getShared produced a fresh instance or an existing one

public array getServices ()

Return the services registered in the DI

public mixed __call (string $method, array $arguments)

Magic method to get or set services using setters/getters

public static setDefault (Phalcon\DiInterface $dependencyInjector)

Set a default dependency injection container to be obtained into static methods

public static Phalcon\DiInterface getDefault ()

Return the lastest DI created

public static reset ()

Resets the internal default DI

Class Phalcon\DI\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\DI\FactoryDefault

extends Phalcon\DI

implements Phalcon\DiInterface

This is a variant of the standard Phalcon\DI. By default it automatically registers all the services provided by the framework. Thanks to this, the developer does not need to register each service individually.

Methods

public __construct ()

Phalcon\DI\FactoryDefault constructor

public Phalcon\Di\ServiceInterface set (string $name, mixed $config, boolean $shared) inherited from Phalcon\DI

Registers a service in the services container

public Phalcon\Di\ServiceInterface setShared (string $name, mixed $config) inherited from Phalcon\DI

Registers an “always shared” service in the services container

public remove (string $name) inherited from Phalcon\DI

Removes a service in the services container

public Phalcon\Di\ServiceInterface attempt (string $name, mixed $config, unknown $shared) inherited from Phalcon\DI

Attempts to register a service in the services container Only is successful if a service hasn’t been registered previously with the same name

public mixed getRaw (string $name) inherited from Phalcon\DI

Returns a service definition without resolving

public Phalcon\Di\ServiceInterface getService (unknown $name) inherited from Phalcon\DI

Returns a Phalcon\Di\Service instance

public mixed get (string $name, array $parameters) inherited from Phalcon\DI

Resolves the service based on its configuration

public mixed getShared (string $name, array $parameters) inherited from Phalcon\DI

Returns a shared service based on their configuration

public boolean has (string $name) inherited from Phalcon\DI

Check whether the DI contains a service by a name

public boolean wasFreshInstance () inherited from Phalcon\DI

Check whether the last service obtained via getShared produced a fresh instance or an existing one

public array getServices () inherited from Phalcon\DI

Return the services registered in the DI

public mixed __call (string $method, array $arguments) inherited from Phalcon\DI

Magic method to get or set services using setters/getters

public static setDefault (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI

Set a default dependency injection container to be obtained into static methods

public static Phalcon\DiInterface getDefault () inherited from Phalcon\DI

Return the lastest DI created

public static reset () inherited from Phalcon\DI

Resets the internal default DI

Class Phalcon\DI\FactoryDefault\CLI

extends Phalcon\DI\FactoryDefault

implements Phalcon\DiInterface

This is a variant of the standard Phalcon\DI. By default it automatically registers all the services provided by the framework. Thanks to this, the developer does not need to register each service individually. This class is specially suitable for CLI applications

Methods

public __construct ()

Phalcon\DI\FactoryDefault\CLI constructor

public Phalcon\Di\ServiceInterface set (string $name, mixed $config, boolean $shared) inherited from Phalcon\DI

Registers a service in the services container

public Phalcon\Di\ServiceInterface setShared (string $name, mixed $config) inherited from Phalcon\DI

Registers an “always shared” service in the services container

public remove (string $name) inherited from Phalcon\DI

Removes a service in the services container

public Phalcon\Di\ServiceInterface attempt (string $name, mixed $config, unknown $shared) inherited from Phalcon\DI

Attempts to register a service in the services container Only is successful if a service hasn’t been registered previously with the same name

public mixed getRaw (string $name) inherited from Phalcon\DI

Returns a service definition without resolving

public Phalcon\Di\ServiceInterface getService (unknown $name) inherited from Phalcon\DI

Returns a Phalcon\Di\Service instance

public mixed get (string $name, array $parameters) inherited from Phalcon\DI

Resolves the service based on its configuration

public mixed getShared (string $name, array $parameters) inherited from Phalcon\DI

Returns a shared service based on their configuration

public boolean has (string $name) inherited from Phalcon\DI

Check whether the DI contains a service by a name

public boolean wasFreshInstance () inherited from Phalcon\DI

Check whether the last service obtained via getShared produced a fresh instance or an existing one

public array getServices () inherited from Phalcon\DI

Return the services registered in the DI

public mixed __call (string $method, array $arguments) inherited from Phalcon\DI

Magic method to get or set services using setters/getters

public static setDefault (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI

Set a default dependency injection container to be obtained into static methods

public static Phalcon\DiInterface getDefault () inherited from Phalcon\DI

Return the lastest DI created

public static reset () inherited from Phalcon\DI

Resets the internal default DI

Class Phalcon\DI\Injectable

implements Phalcon\DI\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

This class allows to access services in the services container by just only accessing a public property with the same name of a registered service

Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

public __get (string $propertyName)

Magic method __get

Class Phalcon\DI\Service

implements Phalcon\DI\ServiceInterface

Represents individually a service in the services container

Methods

public __construct (string $name, mixed $definition, boolean $shared)

public getName ()

Returns the service’s name

public setShared (boolean $shared)

Sets if the service is shared or not

public boolean isShared ()

Check whether the service is shared or not

public setDefinition (mixed $definition)

Set the service definition

public mixed getDefinition ()

Returns the service definition

public mixed resolve (unknown $parameters)

Resolves the service

public static Phalcon\DI\Service __set_state (array $attributes)

Restore the interal state of a service

Class Phalcon\Db

Constants

integer FETCH_ASSOC

integer FETCH_BOTH

integer FETCH_NUM

integer FETCH_OBJ

Class Phalcon\Db\Adapter

implements Phalcon\Events\EventsAwareInterface

Base class for Phalcon\Db adapters

Methods

protected __construct ()

Phalcon\Db\Adapter constructor

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

public array fetchOne (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes)

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fecthOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes)

Dumps the complete result of a query into an array

<?php

//Getting all robots
$robots = $connection->fetchAll("SELECT * FROM robots");
foreach($robots as $robot){
    print_r($robot);
}

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach($robots as $robot){
    print_r($robot);
}

public boolean insert (string $table, array $values, array $fields, array $dataTypes)

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string $table, array $fields, array $values, string $whereCondition, array $dataTypes)

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
     "robots",
     array("name")
     array("New Astro Boy"),
     "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string $table, string $whereCondition, array $placeholders, array $dataTypes)

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
     "robots",
     "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList)

Gets a list of columns

public string limit (string $sqlQuery, int $number)

Appends a LIMIT clause to $sqlQuery argument

<?php

 $connection->limit("SELECT * FROM robots", 5);

public string tableExists (string $tableName, string $schemaName)

Generates SQL checking for the existence of a schema.table

<?php

 $connection->tableExists("blog", "posts")

public string viewExists (string $viewName, string $schemaName)

Generates SQL checking for the existence of a schema.view

<?php

 $connection->viewExists("active_users", "posts")

public string forUpdate (string $sqlQuery)

Returns a SQL modified with a FOR UPDATE clause

public string sharedLock (string $sqlQuery)

Returns a SQL modified with a LOCK IN SHARE MODE clause

public boolean createTable (string $tableName, string $schemaName, array $definition)

Creates a table

public boolean dropTable (string $tableName, string $schemaName, boolean $ifExists)

Drops a table from a schema/database

public boolean addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Adds a column to a table

public boolean modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Modifies a table column based on a definition

public boolean dropColumn (string $tableName, string $schemaName, string $columnName)

Drops a column from a table

public boolean addIndex (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Adds an index to a table

public boolean dropIndex (string $tableName, string $schemaName, string $indexName)

Drop an index from a table

public boolean addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Adds a primary key to a table

public boolean dropPrimaryKey (string $tableName, string $schemaName)

Drops primary key from a table

public boolean true addForeignKey (string $tableName, string $schemaName, Phalcon\Db\ReferenceInterface $reference)

Adds a foreign key to a table

public boolean true dropForeignKey (string $tableName, string $schemaName, string $referenceName)

Drops a foreign key from a table

public string getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Returns the SQL column definition from a column

public array listTables (string $schemaName)

List all tables on a database <code> print_r($connection->listTables(“blog”) ?>

public array getDescriptor ()

Return descriptor used to connect to the active database

public string getConnectionId ()

Gets the active connection unique identifier

public string getSQLStatement ()

Active SQL statement in the object

public string getRealSQLStatement ()

Active SQL statement in the object without replace bound paramters

public array getSQLVariables ()

Active SQL statement in the object

public array getSQLBindTypes ()

Active SQL statement in the object

public string getType ()

Returns type of database system the adapter is used for

public string getDialectType ()

Returns the name of the dialect used

public Phalcon\Db\DialectInterface getDialect ()

Returns internal dialect instance

Class Phalcon\Db\Adapter\Pdo

extends Phalcon\Db\Adapter

implements Phalcon\Events\EventsAwareInterface

Phalcon\Db\Adapter\Pdo is the Phalcon\Db that internally uses PDO to connect to a database

<?php

 $connection = new Phalcon\Db\Adapter\Pdo\Mysql(array(
  'host' => '192.168.0.11',
  'username' => 'sigma',
  'password' => 'secret',
  'dbname' => 'blog',
  'port' => '3306',
 ));
Methods

public __construct (array $descriptor)

Constructor for Phalcon\Db\Adapter\Pdo

public boolean connect (array $descriptor)

This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection

public PDOStatement executePrepared (PDOStatement $statement, array $placeholders, array $dataTypes)

Executes a prepared statement binding

public Phalcon\Db\ResultInterface query (string $sqlStatement, array $bindParams, array $bindTypes)

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows

<?php

//Querying data

$resultset = $connection->query(“SELECT * FROM robots WHERE type=’mechanical’”); $resultset = $connection->query(“SELECT * FROM robots WHERE type=?”, array(“mechanical”));

public boolean execute (string $sqlStatement, unknown $bindParams, unknown $bindTypes)

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server don’t return any row

<?php

//Inserting data
$success = $connection->execute("INSERT INTO robots VALUES (1, 'Astro Boy')");
$success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy'));

public int affectedRows ()

Returns the number of affected rows by the last INSERT/UPDATE/DELETE reported by the database system

<?php

$connection->query("DELETE FROM robots");
echo $connection->affectedRows(), ' were deleted';

public boolean close ()

Closes active connection returning success. Phalcon automatically closes and destroys active connections within Phalcon\Db\Pool

public string escapeIdentifier (string $identifier)

Escapes a column/table/schema name

public string escapeString (string $str)

Escapes a value to avoid SQL injections

public bindParams (unknown $sqlStatement, array $params)

Bind params to a SQL statement

public array convertBoundParams (string $sql, array $params)

Converts bound params such as :name: or ?1 into PDO bind params ?

public int lastInsertId (string $sequenceName)

Returns insert id for the auto_increment column inserted in the last SQL statement

public boolean begin ()

Starts a transaction in the connection

public boolean rollback ()

Rollbacks the active transaction in the connection

public boolean commit ()

Commits the active transaction in the connection

public boolean isUnderTransaction ()

Checks whether connection is under database transaction

public PDO getInternalHandler ()

Return internal PDO handler

public Phalcon\Db\Index [] describeIndexes (string $table, string $schema)

Lists table indexes

public Phalcon\Db\Reference [] describeReferences (string $table, string $schema)

Lists table references

public array tableOptions (string $tableName, string $schemaName)

Gets creation options from a table

public Phalcon\Db\RawValue getDefaultIdValue ()

Return the default identity value to insert in an identity column

public boolean supportSequences ()

Check whether the database system requires a sequence to produce auto-numeric values

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Db\Adapter

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\Db\Adapter

Returns the internal event manager

public array fetchOne (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fecthOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter

Dumps the complete result of a query into an array

<?php

//Getting all robots
$robots = $connection->fetchAll("SELECT * FROM robots");
foreach($robots as $robot){
    print_r($robot);
}

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach($robots as $robot){
    print_r($robot);
}

public boolean insert (string $table, array $values, array $fields, array $dataTypes) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string $table, array $fields, array $values, string $whereCondition, array $dataTypes) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
     "robots",
     array("name")
     array("New Astro Boy"),
     "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string $table, string $whereCondition, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
     "robots",
     "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList) inherited from Phalcon\Db\Adapter

Gets a list of columns

public string limit (string $sqlQuery, int $number) inherited from Phalcon\Db\Adapter

Appends a LIMIT clause to $sqlQuery argument

<?php

 $connection->limit("SELECT * FROM robots", 5);

public string tableExists (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.table

<?php

 $connection->tableExists("blog", "posts")

public string viewExists (string $viewName, string $schemaName) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.view

<?php

 $connection->viewExists("active_users", "posts")

public string forUpdate (string $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a FOR UPDATE clause

public string sharedLock (string $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a LOCK IN SHARE MODE clause

public boolean createTable (string $tableName, string $schemaName, array $definition) inherited from Phalcon\Db\Adapter

Creates a table

public boolean dropTable (string $tableName, string $schemaName, boolean $ifExists) inherited from Phalcon\Db\Adapter

Drops a table from a schema/database

public boolean addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Adds a column to a table

public boolean modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Modifies a table column based on a definition

public boolean dropColumn (string $tableName, string $schemaName, string $columnName) inherited from Phalcon\Db\Adapter

Drops a column from a table

public boolean addIndex (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds an index to a table

public boolean dropIndex (string $tableName, string $schemaName, string $indexName) inherited from Phalcon\Db\Adapter

Drop an index from a table

public boolean addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds a primary key to a table

public boolean dropPrimaryKey (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter

Drops primary key from a table

public boolean true addForeignKey (string $tableName, string $schemaName, Phalcon\Db\ReferenceInterface $reference) inherited from Phalcon\Db\Adapter

Adds a foreign key to a table

public boolean true dropForeignKey (string $tableName, string $schemaName, string $referenceName) inherited from Phalcon\Db\Adapter

Drops a foreign key from a table

public string getColumnDefinition (Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Returns the SQL column definition from a column

public array listTables (string $schemaName) inherited from Phalcon\Db\Adapter

List all tables on a database <code> print_r($connection->listTables(“blog”) ?>

public array getDescriptor () inherited from Phalcon\Db\Adapter

Return descriptor used to connect to the active database

public string getConnectionId () inherited from Phalcon\Db\Adapter

Gets the active connection unique identifier

public string getSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public string getRealSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object without replace bound paramters

public array getSQLVariables () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public array getSQLBindTypes () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public string getType () inherited from Phalcon\Db\Adapter

Returns type of database system the adapter is used for

public string getDialectType () inherited from Phalcon\Db\Adapter

Returns the name of the dialect used

public Phalcon\Db\DialectInterface getDialect () inherited from Phalcon\Db\Adapter

Returns internal dialect instance

Class Phalcon\Db\Adapter\Pdo\Mysql

extends Phalcon\Db\Adapter\Pdo

implements Phalcon\Events\EventsAwareInterface, Phalcon\Db\AdapterInterface

Specific functions for the Mysql database system

<?php

$config = array(
    "host" => "192.168.0.11",
    "dbname" => "blog",
    "port" => 3306,
    "username" => "sigma",
    "password" => "secret"
);

$connection = new Phalcon\Db\Adapter\Pdo\Mysql($config);
Methods

public string escapeIdentifier (string $identifier)

Escapes a column/table/schema name

public Phalcon\Db\Column [] describeColumns (string $table, string $schema)

Returns an array of Phalcon\Db\Column objects describing a table

<?php

 print_r($connection->describeColumns("posts")); ?>

public __construct (array $descriptor) inherited from Phalcon\Db\Adapter\Pdo

Constructor for Phalcon\Db\Adapter\Pdo

public boolean connect (array $descriptor) inherited from Phalcon\Db\Adapter\Pdo

This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection

public PDOStatement executePrepared (PDOStatement $statement, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter\Pdo

Executes a prepared statement binding

public Phalcon\Db\ResultInterface query (string $sqlStatement, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows

<?php

//Querying data

$resultset = $connection->query(“SELECT * FROM robots WHERE type=’mechanical’”); $resultset = $connection->query(“SELECT * FROM robots WHERE type=?”, array(“mechanical”));

public boolean execute (string $sqlStatement, unknown $bindParams, unknown $bindTypes) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server don’t return any row

<?php

//Inserting data
$success = $connection->execute("INSERT INTO robots VALUES (1, 'Astro Boy')");
$success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy'));

public int affectedRows () inherited from Phalcon\Db\Adapter\Pdo

Returns the number of affected rows by the last INSERT/UPDATE/DELETE reported by the database system

<?php

$connection->query("DELETE FROM robots");
echo $connection->affectedRows(), ' were deleted';

public boolean close () inherited from Phalcon\Db\Adapter\Pdo

Closes active connection returning success. Phalcon automatically closes and destroys active connections within Phalcon\Db\Pool

public string escapeString (string $str) inherited from Phalcon\Db\Adapter\Pdo

Escapes a value to avoid SQL injections

public bindParams (unknown $sqlStatement, array $params) inherited from Phalcon\Db\Adapter\Pdo

Bind params to a SQL statement

public array convertBoundParams (string $sql, array $params) inherited from Phalcon\Db\Adapter\Pdo

Converts bound params such as :name: or ?1 into PDO bind params ?

public int lastInsertId (string $sequenceName) inherited from Phalcon\Db\Adapter\Pdo

Returns insert id for the auto_increment column inserted in the last SQL statement

public boolean begin () inherited from Phalcon\Db\Adapter\Pdo

Starts a transaction in the connection

public boolean rollback () inherited from Phalcon\Db\Adapter\Pdo

Rollbacks the active transaction in the connection

public boolean commit () inherited from Phalcon\Db\Adapter\Pdo

Commits the active transaction in the connection

public boolean isUnderTransaction () inherited from Phalcon\Db\Adapter\Pdo

Checks whether connection is under database transaction

public PDO getInternalHandler () inherited from Phalcon\Db\Adapter\Pdo

Return internal PDO handler

public Phalcon\Db\Index [] describeIndexes (string $table, string $schema) inherited from Phalcon\Db\Adapter\Pdo

Lists table indexes

public Phalcon\Db\Reference [] describeReferences (string $table, string $schema) inherited from Phalcon\Db\Adapter\Pdo

Lists table references

public array tableOptions (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter\Pdo

Gets creation options from a table

public Phalcon\Db\RawValue getDefaultIdValue () inherited from Phalcon\Db\Adapter\Pdo

Return the default identity value to insert in an identity column

public boolean supportSequences () inherited from Phalcon\Db\Adapter\Pdo

Check whether the database system requires a sequence to produce auto-numeric values

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Db\Adapter

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\Db\Adapter

Returns the internal event manager

public array fetchOne (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fecthOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter

Dumps the complete result of a query into an array

<?php

//Getting all robots
$robots = $connection->fetchAll("SELECT * FROM robots");
foreach($robots as $robot){
    print_r($robot);
}

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach($robots as $robot){
    print_r($robot);
}

public boolean insert (string $table, array $values, array $fields, array $dataTypes) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string $table, array $fields, array $values, string $whereCondition, array $dataTypes) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
     "robots",
     array("name")
     array("New Astro Boy"),
     "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string $table, string $whereCondition, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
     "robots",
     "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList) inherited from Phalcon\Db\Adapter

Gets a list of columns

public string limit (string $sqlQuery, int $number) inherited from Phalcon\Db\Adapter

Appends a LIMIT clause to $sqlQuery argument

<?php

 $connection->limit("SELECT * FROM robots", 5);

public string tableExists (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.table

<?php

 $connection->tableExists("blog", "posts")

public string viewExists (string $viewName, string $schemaName) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.view

<?php

 $connection->viewExists("active_users", "posts")

public string forUpdate (string $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a FOR UPDATE clause

public string sharedLock (string $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a LOCK IN SHARE MODE clause

public boolean createTable (string $tableName, string $schemaName, array $definition) inherited from Phalcon\Db\Adapter

Creates a table

public boolean dropTable (string $tableName, string $schemaName, boolean $ifExists) inherited from Phalcon\Db\Adapter

Drops a table from a schema/database

public boolean addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Adds a column to a table

public boolean modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Modifies a table column based on a definition

public boolean dropColumn (string $tableName, string $schemaName, string $columnName) inherited from Phalcon\Db\Adapter

Drops a column from a table

public boolean addIndex (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds an index to a table

public boolean dropIndex (string $tableName, string $schemaName, string $indexName) inherited from Phalcon\Db\Adapter

Drop an index from a table

public boolean addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds a primary key to a table

public boolean dropPrimaryKey (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter

Drops primary key from a table

public boolean true addForeignKey (string $tableName, string $schemaName, Phalcon\Db\ReferenceInterface $reference) inherited from Phalcon\Db\Adapter

Adds a foreign key to a table

public boolean true dropForeignKey (string $tableName, string $schemaName, string $referenceName) inherited from Phalcon\Db\Adapter

Drops a foreign key from a table

public string getColumnDefinition (Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Returns the SQL column definition from a column

public array listTables (string $schemaName) inherited from Phalcon\Db\Adapter

List all tables on a database <code> print_r($connection->listTables(“blog”) ?>

public array getDescriptor () inherited from Phalcon\Db\Adapter

Return descriptor used to connect to the active database

public string getConnectionId () inherited from Phalcon\Db\Adapter

Gets the active connection unique identifier

public string getSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public string getRealSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object without replace bound paramters

public array getSQLVariables () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public array getSQLBindTypes () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public string getType () inherited from Phalcon\Db\Adapter

Returns type of database system the adapter is used for

public string getDialectType () inherited from Phalcon\Db\Adapter

Returns the name of the dialect used

public Phalcon\Db\DialectInterface getDialect () inherited from Phalcon\Db\Adapter

Returns internal dialect instance

Class Phalcon\Db\Adapter\Pdo\Postgresql

extends Phalcon\Db\Adapter\Pdo

implements Phalcon\Events\EventsAwareInterface, Phalcon\Db\AdapterInterface

Specific functions for the Postgresql database system

<?php

 $config = array(
  "host" => "192.168.0.11",
  "dbname" => "blog",
  "username" => "postgres",
  "password" => ""
 );

 $connection = new Phalcon\Db\Adapter\Pdo\Postgresql($config);
Methods

public boolean connect (array $descriptor)

This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection. Support set search_path after connectted if schema is specified in config.

public Phalcon\Db\Column [] describeColumns (string $table, string $schema)

Returns an array of Phalcon\Db\Column objects describing a table <code>print_r($connection->describeColumns(“posts”)); ?>

public Phalcon\Db\RawValue getDefaultIdValue ()

Return the default identity value to insert in an identity column

public boolean supportSequences ()

Check whether the database system requires a sequence to produce auto-numeric values

public __construct (array $descriptor) inherited from Phalcon\Db\Adapter\Pdo

Constructor for Phalcon\Db\Adapter\Pdo

public PDOStatement executePrepared (PDOStatement $statement, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter\Pdo

Executes a prepared statement binding

public Phalcon\Db\ResultInterface query (string $sqlStatement, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows

<?php

//Querying data

$resultset = $connection->query(“SELECT * FROM robots WHERE type=’mechanical’”); $resultset = $connection->query(“SELECT * FROM robots WHERE type=?”, array(“mechanical”));

public boolean execute (string $sqlStatement, unknown $bindParams, unknown $bindTypes) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server don’t return any row

<?php

//Inserting data
$success = $connection->execute("INSERT INTO robots VALUES (1, 'Astro Boy')");
$success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy'));

public int affectedRows () inherited from Phalcon\Db\Adapter\Pdo

Returns the number of affected rows by the last INSERT/UPDATE/DELETE reported by the database system

<?php

$connection->query("DELETE FROM robots");
echo $connection->affectedRows(), ' were deleted';

public boolean close () inherited from Phalcon\Db\Adapter\Pdo

Closes active connection returning success. Phalcon automatically closes and destroys active connections within Phalcon\Db\Pool

public string escapeIdentifier (string $identifier) inherited from Phalcon\Db\Adapter\Pdo

Escapes a column/table/schema name

public string escapeString (string $str) inherited from Phalcon\Db\Adapter\Pdo

Escapes a value to avoid SQL injections

public bindParams (unknown $sqlStatement, array $params) inherited from Phalcon\Db\Adapter\Pdo

Bind params to a SQL statement

public array convertBoundParams (string $sql, array $params) inherited from Phalcon\Db\Adapter\Pdo

Converts bound params such as :name: or ?1 into PDO bind params ?

public int lastInsertId (string $sequenceName) inherited from Phalcon\Db\Adapter\Pdo

Returns insert id for the auto_increment column inserted in the last SQL statement

public boolean begin () inherited from Phalcon\Db\Adapter\Pdo

Starts a transaction in the connection

public boolean rollback () inherited from Phalcon\Db\Adapter\Pdo

Rollbacks the active transaction in the connection

public boolean commit () inherited from Phalcon\Db\Adapter\Pdo

Commits the active transaction in the connection

public boolean isUnderTransaction () inherited from Phalcon\Db\Adapter\Pdo

Checks whether connection is under database transaction

public PDO getInternalHandler () inherited from Phalcon\Db\Adapter\Pdo

Return internal PDO handler

public Phalcon\Db\Index [] describeIndexes (string $table, string $schema) inherited from Phalcon\Db\Adapter\Pdo

Lists table indexes

public Phalcon\Db\Reference [] describeReferences (string $table, string $schema) inherited from Phalcon\Db\Adapter\Pdo

Lists table references

public array tableOptions (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter\Pdo

Gets creation options from a table

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Db\Adapter

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\Db\Adapter

Returns the internal event manager

public array fetchOne (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fecthOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter

Dumps the complete result of a query into an array

<?php

//Getting all robots
$robots = $connection->fetchAll("SELECT * FROM robots");
foreach($robots as $robot){
    print_r($robot);
}

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach($robots as $robot){
    print_r($robot);
}

public boolean insert (string $table, array $values, array $fields, array $dataTypes) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string $table, array $fields, array $values, string $whereCondition, array $dataTypes) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
     "robots",
     array("name")
     array("New Astro Boy"),
     "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string $table, string $whereCondition, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
     "robots",
     "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList) inherited from Phalcon\Db\Adapter

Gets a list of columns

public string limit (string $sqlQuery, int $number) inherited from Phalcon\Db\Adapter

Appends a LIMIT clause to $sqlQuery argument

<?php

 $connection->limit("SELECT * FROM robots", 5);

public string tableExists (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.table

<?php

 $connection->tableExists("blog", "posts")

public string viewExists (string $viewName, string $schemaName) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.view

<?php

 $connection->viewExists("active_users", "posts")

public string forUpdate (string $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a FOR UPDATE clause

public string sharedLock (string $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a LOCK IN SHARE MODE clause

public boolean createTable (string $tableName, string $schemaName, array $definition) inherited from Phalcon\Db\Adapter

Creates a table

public boolean dropTable (string $tableName, string $schemaName, boolean $ifExists) inherited from Phalcon\Db\Adapter

Drops a table from a schema/database

public boolean addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Adds a column to a table

public boolean modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Modifies a table column based on a definition

public boolean dropColumn (string $tableName, string $schemaName, string $columnName) inherited from Phalcon\Db\Adapter

Drops a column from a table

public boolean addIndex (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds an index to a table

public boolean dropIndex (string $tableName, string $schemaName, string $indexName) inherited from Phalcon\Db\Adapter

Drop an index from a table

public boolean addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds a primary key to a table

public boolean dropPrimaryKey (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter

Drops primary key from a table

public boolean true addForeignKey (string $tableName, string $schemaName, Phalcon\Db\ReferenceInterface $reference) inherited from Phalcon\Db\Adapter

Adds a foreign key to a table

public boolean true dropForeignKey (string $tableName, string $schemaName, string $referenceName) inherited from Phalcon\Db\Adapter

Drops a foreign key from a table

public string getColumnDefinition (Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Returns the SQL column definition from a column

public array listTables (string $schemaName) inherited from Phalcon\Db\Adapter

List all tables on a database <code> print_r($connection->listTables(“blog”) ?>

public array getDescriptor () inherited from Phalcon\Db\Adapter

Return descriptor used to connect to the active database

public string getConnectionId () inherited from Phalcon\Db\Adapter

Gets the active connection unique identifier

public string getSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public string getRealSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object without replace bound paramters

public array getSQLVariables () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public array getSQLBindTypes () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public string getType () inherited from Phalcon\Db\Adapter

Returns type of database system the adapter is used for

public string getDialectType () inherited from Phalcon\Db\Adapter

Returns the name of the dialect used

public Phalcon\Db\DialectInterface getDialect () inherited from Phalcon\Db\Adapter

Returns internal dialect instance

Class Phalcon\Db\Adapter\Pdo\Sqlite

extends Phalcon\Db\Adapter\Pdo

implements Phalcon\Events\EventsAwareInterface, Phalcon\Db\AdapterInterface

Specific functions for the Sqlite database system

<?php

 $config = array(
  "dbname" => "/tmp/test.sqlite"
 );

 $connection = new Phalcon\Db\Adapter\Pdo\Sqlite($config);
Methods

public boolean connect (array $descriptor)

This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection.

public Phalcon\Db\Column [] describeColumns (string $table, string $schema)

Returns an array of Phalcon\Db\Column objects describing a table

<?php

 print_r($connection->describeColumns("posts")); ?>

public Phalcon\Db\Index [] describeIndexes (string $table, string $schema)

Lists table indexes

public Phalcon\Db\Reference [] describeReferences (string $table, string $schema)

Lists table references

public __construct (array $descriptor) inherited from Phalcon\Db\Adapter\Pdo

Constructor for Phalcon\Db\Adapter\Pdo

public PDOStatement executePrepared (PDOStatement $statement, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter\Pdo

Executes a prepared statement binding

public Phalcon\Db\ResultInterface query (string $sqlStatement, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows

<?php

//Querying data

$resultset = $connection->query(“SELECT * FROM robots WHERE type=’mechanical’”); $resultset = $connection->query(“SELECT * FROM robots WHERE type=?”, array(“mechanical”));

public boolean execute (string $sqlStatement, unknown $bindParams, unknown $bindTypes) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server don’t return any row

<?php

//Inserting data
$success = $connection->execute("INSERT INTO robots VALUES (1, 'Astro Boy')");
$success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy'));

public int affectedRows () inherited from Phalcon\Db\Adapter\Pdo

Returns the number of affected rows by the last INSERT/UPDATE/DELETE reported by the database system

<?php

$connection->query("DELETE FROM robots");
echo $connection->affectedRows(), ' were deleted';

public boolean close () inherited from Phalcon\Db\Adapter\Pdo

Closes active connection returning success. Phalcon automatically closes and destroys active connections within Phalcon\Db\Pool

public string escapeIdentifier (string $identifier) inherited from Phalcon\Db\Adapter\Pdo

Escapes a column/table/schema name

public string escapeString (string $str) inherited from Phalcon\Db\Adapter\Pdo

Escapes a value to avoid SQL injections

public bindParams (unknown $sqlStatement, array $params) inherited from Phalcon\Db\Adapter\Pdo

Bind params to a SQL statement

public array convertBoundParams (string $sql, array $params) inherited from Phalcon\Db\Adapter\Pdo

Converts bound params such as :name: or ?1 into PDO bind params ?

public int lastInsertId (string $sequenceName) inherited from Phalcon\Db\Adapter\Pdo

Returns insert id for the auto_increment column inserted in the last SQL statement

public boolean begin () inherited from Phalcon\Db\Adapter\Pdo

Starts a transaction in the connection

public boolean rollback () inherited from Phalcon\Db\Adapter\Pdo

Rollbacks the active transaction in the connection

public boolean commit () inherited from Phalcon\Db\Adapter\Pdo

Commits the active transaction in the connection

public boolean isUnderTransaction () inherited from Phalcon\Db\Adapter\Pdo

Checks whether connection is under database transaction

public PDO getInternalHandler () inherited from Phalcon\Db\Adapter\Pdo

Return internal PDO handler

public array tableOptions (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter\Pdo

Gets creation options from a table

public Phalcon\Db\RawValue getDefaultIdValue () inherited from Phalcon\Db\Adapter\Pdo

Return the default identity value to insert in an identity column

public boolean supportSequences () inherited from Phalcon\Db\Adapter\Pdo

Check whether the database system requires a sequence to produce auto-numeric values

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Db\Adapter

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\Db\Adapter

Returns the internal event manager

public array fetchOne (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fecthOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, int $fetchMode, array $bindParams, array $bindTypes) inherited from Phalcon\Db\Adapter

Dumps the complete result of a query into an array

<?php

//Getting all robots
$robots = $connection->fetchAll("SELECT * FROM robots");
foreach($robots as $robot){
    print_r($robot);
}

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach($robots as $robot){
    print_r($robot);
}

public boolean insert (string $table, array $values, array $fields, array $dataTypes) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string $table, array $fields, array $values, string $whereCondition, array $dataTypes) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
     "robots",
     array("name")
     array("New Astro Boy"),
     "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string $table, string $whereCondition, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
     "robots",
     "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList) inherited from Phalcon\Db\Adapter

Gets a list of columns

public string limit (string $sqlQuery, int $number) inherited from Phalcon\Db\Adapter

Appends a LIMIT clause to $sqlQuery argument

<?php

 $connection->limit("SELECT * FROM robots", 5);

public string tableExists (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.table

<?php

 $connection->tableExists("blog", "posts")

public string viewExists (string $viewName, string $schemaName) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.view

<?php

 $connection->viewExists("active_users", "posts")

public string forUpdate (string $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a FOR UPDATE clause

public string sharedLock (string $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a LOCK IN SHARE MODE clause

public boolean createTable (string $tableName, string $schemaName, array $definition) inherited from Phalcon\Db\Adapter

Creates a table

public boolean dropTable (string $tableName, string $schemaName, boolean $ifExists) inherited from Phalcon\Db\Adapter

Drops a table from a schema/database

public boolean addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Adds a column to a table

public boolean modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Modifies a table column based on a definition

public boolean dropColumn (string $tableName, string $schemaName, string $columnName) inherited from Phalcon\Db\Adapter

Drops a column from a table

public boolean addIndex (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds an index to a table

public boolean dropIndex (string $tableName, string $schemaName, string $indexName) inherited from Phalcon\Db\Adapter

Drop an index from a table

public boolean addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds a primary key to a table

public boolean dropPrimaryKey (string $tableName, string $schemaName) inherited from Phalcon\Db\Adapter

Drops primary key from a table

public boolean true addForeignKey (string $tableName, string $schemaName, Phalcon\Db\ReferenceInterface $reference) inherited from Phalcon\Db\Adapter

Adds a foreign key to a table

public boolean true dropForeignKey (string $tableName, string $schemaName, string $referenceName) inherited from Phalcon\Db\Adapter

Drops a foreign key from a table

public string getColumnDefinition (Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Returns the SQL column definition from a column

public array listTables (string $schemaName) inherited from Phalcon\Db\Adapter

List all tables on a database <code> print_r($connection->listTables(“blog”) ?>

public array getDescriptor () inherited from Phalcon\Db\Adapter

Return descriptor used to connect to the active database

public string getConnectionId () inherited from Phalcon\Db\Adapter

Gets the active connection unique identifier

public string getSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public string getRealSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object without replace bound paramters

public array getSQLVariables () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public array getSQLBindTypes () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public string getType () inherited from Phalcon\Db\Adapter

Returns type of database system the adapter is used for

public string getDialectType () inherited from Phalcon\Db\Adapter

Returns the name of the dialect used

public Phalcon\Db\DialectInterface getDialect () inherited from Phalcon\Db\Adapter

Returns internal dialect instance

Class Phalcon\Db\Column

implements Phalcon\Db\ColumnInterface

Allows to define columns to be used on create or alter table operations

<?php

use Phalcon\Db\Column as Column;

 //column definition
 $column = new Column("id", array(
   "type" => Column::TYPE_INTEGER,
   "size" => 10,
   "unsigned" => true,
   "notNull" => true,
   "autoIncrement" => true,
   "first" => true
 ));

 //add column to existing table
 $connection->addColumn("robots", null, $column);
Constants

integer TYPE_INTEGER

integer TYPE_DATE

integer TYPE_VARCHAR

integer TYPE_DECIMAL

integer TYPE_DATETIME

integer TYPE_CHAR

integer TYPE_TEXT

integer TYPE_FLOAT

integer BIND_PARAM_NULL

integer BIND_PARAM_INT

integer BIND_PARAM_STR

integer BIND_PARAM_DECIMAL

integer BIND_SKIP

Methods

public __construct (string $columnName, array $definition)

Phalcon\Db\Column constructor

public string getSchemaName ()

Returns schema’s table related to column

public string getName ()

Returns column name

public int getType ()

Returns column type

public int getSize ()

Returns column size

public int getScale ()

Returns column scale

public boolean isUnsigned ()

Returns true if number column is unsigned

public boolean isNotNull ()

Not null

public boolean isPrimary ()

Column is part of the primary key?

public boolean isAutoIncrement ()

Auto-Increment

public boolean isNumeric ()

Check whether column have an numeric type

public boolean isFirst ()

Check whether column have first position in table

public string getAfterPosition ()

Check whether field absolute to position in table

public int getBindType ()

Returns the type of bind handling

public static PhalconDbColumn __set_state (array $data)

Restores the internal state of a Phalcon\Db\Column object

Class Phalcon\Db\Dialect

This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBM related syntax

Methods

public string limit (string $sqlQuery, int $number)

Generates the SQL for LIMIT clause

public string forUpdate (string $sqlQuery)

Returns a SQL modified with a FOR UPDATE clause

public string sharedLock (string $sqlQuery)

Returns a SQL modified with a LOCK IN SHARE MODE clause

public string getColumnList (array $columnList)

Gets a list of columns

public string getSqlExpression (array $expression, string $escapeChar)

Transform an intermediate representation for a expression into a database system valid expression

public string getSqlTable (unknown $table, string $escapeChar)

Transform an intermediate representation for a schema/table into a database system valid expression

public string select (array $definition)

Builds a SELECT statement

Class Phalcon\Db\Dialect\Mysql

extends Phalcon\Db\Dialect

implements Phalcon\Db\DialectInterface

Generates database specific SQL for the MySQL RBDM

Methods

public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Gets the column name in MySQL

public string addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to add a column to a table

public string modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to modify a column in a table

public string dropColumn (string $tableName, string $schemaName, string $columnName)

Generates SQL to delete a column from a table

public string addIndex (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add an index to a table

public string dropIndex (string $tableName, string $schemaName, string $indexName)

Generates SQL to delete an index from a table

public string addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add the primary key to a table

public string dropPrimaryKey (string $tableName, string $schemaName)

Generates SQL to delete primary key from a table

public string addForeignKey (string $tableName, string $schemaName, Phalcon\Db\ReferenceInterface $reference)

Generates SQL to add an index to a table

public string dropForeignKey (string $tableName, string $schemaName, string $referenceName)

Generates SQL to delete a foreign key from a table

protected array _getTableOptions ()

Generates SQL to add the table creation options

public string createTable (string $tableName, string $schemaName, array $definition)

Generates SQL to create a table in MySQL

public boolean dropTable (string $tableName, string $schemaName, boolean $ifExists)

Generates SQL to drop a table

public string tableExists (string $tableName, string $schemaName)

Generates SQL checking for the existence of a schema.table <code>echo $dialect->tableExists(“posts”, “blog”) <code>echo $dialect->tableExists(“posts”)

public string describeColumns (string $table, string $schema)

Generates SQL describing a table <code>print_r($dialect->describeColumns(“posts”) ?>

public array listTables (string $schemaName)

List all tables on database <code>print_r($dialect->listTables(“blog”) ?>

public string describeIndexes (string $table, string $schema)

Generates SQL to query indexes on a table

public string describeReferences (string $table, string $schema)

Generates SQL to query foreign keys on a table

public string tableOptions (string $table, string $schema)

Generates the SQL to describe the table creation options

public string limit (string $sqlQuery, int $number) inherited from Phalcon\Db\Dialect

Generates the SQL for LIMIT clause

public string forUpdate (string $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a FOR UPDATE clause

public string sharedLock (string $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a LOCK IN SHARE MODE clause

public string getColumnList (array $columnList) inherited from Phalcon\Db\Dialect

Gets a list of columns

public string getSqlExpression (array $expression, string $escapeChar) inherited from Phalcon\Db\Dialect

Transform an intermediate representation for a expression into a database system valid expression

public string getSqlTable (unknown $table, string $escapeChar) inherited from Phalcon\Db\Dialect

Transform an intermediate representation for a schema/table into a database system valid expression

public string select (array $definition) inherited from Phalcon\Db\Dialect

Builds a SELECT statement

Class Phalcon\Db\Dialect\Postgresql

extends Phalcon\Db\Dialect

implements Phalcon\Db\DialectInterface

Generates database specific SQL for the PostgreSQL RBDM

Methods

public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Gets the column name in PostgreSQL

public string addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to add a column to a table

public string modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to modify a column in a table

public string dropColumn (string $tableName, string $schemaName, string $columnName)

Generates SQL to delete a column from a table

public string addIndex (string $tableName, string $schemaName, Phalcon\Db\Index $index)

Generates SQL to add an index to a table

public string dropIndex (string $tableName, string $schemaName, string $indexName)

Generates SQL to delete an index from a table

public string addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\Index $index)

Generates SQL to add the primary key to a table

public string dropPrimaryKey (string $tableName, string $schemaName)

Generates SQL to delete primary key from a table

public string addForeignKey (string $tableName, string $schemaName, Phalcon\Db\ReferenceInterface $reference)

Generates SQL to add an index to a table

public string dropForeignKey (string $tableName, string $schemaName, string $referenceName)

Generates SQL to delete a foreign key from a table

protected array _getTableOptions ()

Generates SQL to add the table creation options

public string createTable (string $tableName, string $schemaName, array $definition)

Generates SQL to create a table in PostgreSQL

public boolean dropTable (string $tableName, string $schemaName, boolean $ifExists)

Generates SQL to drop a table

public string tableExists (string $tableName, string $schemaName)

Generates SQL checking for the existence of a schema.table <code>echo $dialect->tableExists(“posts”, “blog”) <code>echo $dialect->tableExists(“posts”)

public string describeColumns (string $table, string $schema)

Generates a SQL describing a table <code>print_r($dialect->describeColumns(“posts”) ?>

public array listTables (string $schemaName)

List all tables on database <code>print_r($dialect->listTables(“blog”) ?>

public string describeIndexes (string $table, string $schema)

Generates SQL to query indexes on a table

public string describeReferences (string $table, string $schema)

Generates SQL to query foreign keys on a table

public string tableOptions (string $table, string $schema)

Generates the SQL to describe the table creation options

public string limit (string $sqlQuery, int $number) inherited from Phalcon\Db\Dialect

Generates the SQL for LIMIT clause

public string forUpdate (string $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a FOR UPDATE clause

public string sharedLock (string $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a LOCK IN SHARE MODE clause

public string getColumnList (array $columnList) inherited from Phalcon\Db\Dialect

Gets a list of columns

public string getSqlExpression (array $expression, string $escapeChar) inherited from Phalcon\Db\Dialect

Transform an intermediate representation for a expression into a database system valid expression

public string getSqlTable (unknown $table, string $escapeChar) inherited from Phalcon\Db\Dialect

Transform an intermediate representation for a schema/table into a database system valid expression

public string select (array $definition) inherited from Phalcon\Db\Dialect

Builds a SELECT statement

Class Phalcon\Db\Dialect\Sqlite

extends Phalcon\Db\Dialect

implements Phalcon\Db\DialectInterface

Generates database specific SQL for the Sqlite RBDM

Methods

public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Gets the column name in Sqlite

public string addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to add a column to a table

public string modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to modify a column in a table

public string dropColumn (string $tableName, string $schemaName, string $columnName)

Generates SQL to delete a column from a table

public string addIndex (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add an index to a table

public string dropIndex (string $tableName, string $schemaName, string $indexName)

Generates SQL to delete an index from a table

public string addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add the primary key to a table

public string dropPrimaryKey (string $tableName, string $schemaName)

Generates SQL to delete primary key from a table

public string addForeignKey (string $tableName, string $schemaName, Phalcon\Db\Reference $reference)

Generates SQL to add an index to a table

public string dropForeignKey (string $tableName, string $schemaName, string $referenceName)

Generates SQL to delete a foreign key from a table

protected array _getTableOptions ()

Generates SQL to add the table creation options

public string createTable (string $tableName, string $schemaName, array $definition)

Generates SQL to create a table in PostgreSQL

public boolean dropTable (string $tableName, string $schemaName, boolean $ifExists)

Generates SQL to drop a table

public string tableExists (string $tableName, string $schemaName)

Generates SQL checking for the existence of a schema.table <code>echo $dialect->tableExists(“posts”, “blog”) <code>echo $dialect->tableExists(“posts”)

public string describeColumns (string $table, string $schema)

Generates a SQL describing a table <code>print_r($dialect->describeColumns(“posts”) ?>

public array listTables (string $schemaName)

List all tables on database <code>print_r($dialect->listTables(“blog”) ?>

public string describeIndexes (string $table, string $schema)

Generates SQL to query indexes on a table

public string describeIndex (string $indexName)

Generates SQL to query indexes detail on a table

public string describeReferences (string $table, string $schema)

Generates SQL to query foreign keys on a table

public string tableOptions (string $table, string $schema)

Generates the SQL to describe the table creation options

public string limit (string $sqlQuery, int $number) inherited from Phalcon\Db\Dialect

Generates the SQL for LIMIT clause

public string forUpdate (string $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a FOR UPDATE clause

public string sharedLock (string $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a LOCK IN SHARE MODE clause

public string getColumnList (array $columnList) inherited from Phalcon\Db\Dialect

Gets a list of columns

public string getSqlExpression (array $expression, string $escapeChar) inherited from Phalcon\Db\Dialect

Transform an intermediate representation for a expression into a database system valid expression

public string getSqlTable (unknown $table, string $escapeChar) inherited from Phalcon\Db\Dialect

Transform an intermediate representation for a schema/table into a database system valid expression

public string select (array $definition) inherited from Phalcon\Db\Dialect

Builds a SELECT statement

Class Phalcon\Db\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Db\Index

implements Phalcon\Db\IndexInterface

Allows to define indexes to be used on tables. Indexes are a common way to enhance database performance. An index allows the database server to find and retrieve specific rows much faster than it could do without an index.

Methods

public __construct (string $indexName, array $columns)

Phalcon\Db\Index constructor

public string getName ()

Gets the index name

public array getColumns ()

Gets the columns that comprends the index

public static Phalcon\Db\IndexInterface __set_state (array $data)

Restore a Phalcon\Db\Index object from export

Class Phalcon\Db\Profiler

Instances of Phalcon\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in miliseconds. This helps you to identify bottlenecks in your applications.

<?php

$profiler = new Phalcon\Db\Profiler();

//Set the connection profiler
$connection->setProfiler($profiler);

$sql = "SELECT buyer_name, quantity, product_name
FROM buyers LEFT JOIN products ON
buyers.pid=products.id";

//Execute a SQL statement
$connection->query($sql);

//Get the last profile in the profiler
$profile = $profiler->getLastProfile();

echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
echo "Start Time: ", $profile->getInitialTime(), "\n";
echo "Final Time: ", $profile->getFinalTime(), "\n";
echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";
Methods

public __construct ()

Phalcon\Db\Profiler constructor

public Phalcon\Db\Profiler startProfile (string $sqlStatement)

Starts the profile of a SQL sentence

public Phalcon\Db\Profiler stopProfile ()

Stops the active profile

public integer getNumberTotalStatements ()

Returns the total number of SQL statements processed

public double getTotalElapsedSeconds ()

Returns the total time in seconds spent by the profiles

public Phalcon\Db\Profiler\Item [] getProfiles ()

Returns all the processed profiles

public Phalcon\Db\Profiler reset ()

Resets the profiler, cleaning up all the profiles

public Phalcon\Db\Profiler\Item getLastProfile ()

Returns the last profile executed in the profiler

Class Phalcon\Db\Profiler\Item

This class identifies each profile in a Phalcon\Db\Profiler

Methods

public setSQLStatement (string $sqlStatement)

Sets the SQL statement related to the profile

public string getSQLStatement ()

Returns the SQL statement related to the profile

public setInitialTime (int $initialTime)

Sets the timestamp on when the profile started

public setFinalTime (int $finalTime)

Sets the timestamp on when the profile ended

public double getInitialTime ()

Returns the initial time in milseconds on when the profile started

public double getFinalTime ()

Returns the initial time in milseconds on when the profile ended

public double getTotalElapsedSeconds ()

Returns the total time in seconds spent by the profile

Class Phalcon\Db\RawValue

This class allows to insert/update raw data without quoting or formating. The next example shows how to use the MySQL now() function as a field value.

<?php

$subscriber = new Subscribers();
$subscriber->email = 'andres@phalconphp.com';
$subscriber->created_at = new Phalcon\Db\RawValue('now()');
$subscriber->save();
Methods

public __construct (string $value)

Phalcon\Db\RawValue constructor

public string getValue ()

Returns internal raw value without quoting or formating

public __toString ()

Magic method __toString returns raw value without quoting or formating

Class Phalcon\Db\Reference

implements Phalcon\Db\ReferenceInterface

Allows to define reference constraints on tables

<?php

$reference = new Phalcon\Db\Reference("field_fk", array(
    'referencedSchema' => "invoicing",
    'referencedTable' => "products",
    'columns' => array("product_type", "product_code"),
    'referencedColumns' => array("type", "code")
));
Methods

public __construct (string $referenceName, array $definition)

Phalcon\Db\Reference constructor

public string getName ()

Gets the index name

public string getSchemaName ()

Gets the schema where referenced table is

public string getReferencedSchema ()

Gets the schema where referenced table is

public array getColumns ()

Gets local columns which reference is based

public string getReferencedTable ()

Gets the referenced table

public array getReferencedColumns ()

Gets referenced columns

public static Phalcon\Db\Reference __set_state (array $data)

Restore a Phalcon\Db\Reference object from export

Class Phalcon\Db\Result\Pdo

Encapsulates the resultset internals

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$result->setFetchMode(Phalcon\Db::FETCH_NUM);
while($robot = $result->fetchArray()){
    print_r($robot);
}
Methods

public __construct (Phalcon\Db\AdapterInterface $connection, PDOStatement $result, string $sqlStatement, array $bindParams, array $bindTypes)

Phalcon\Db\Result\Pdo constructor

public boolean execute ()

Allows to executes the statement again. Some database systems don’t support scrollable cursors, So, as cursors are forward only, we need to execute the cursor again to fetch rows from the begining

public mixed fetch ()

Fetches an array/object of strings that corresponds to the fetched row, or FALSE if there are no more rows. This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$result->setFetchMode(Phalcon\Db::FETCH_OBJ);
while($robot = $result->fetch()){
    echo $robot->name;
}

public mixed fetchArray ()

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$result->setFetchMode(Phalcon\Db::FETCH_NUM);
while($robot = $result->fetchArray()){
    print_r($robot);
}

public array fetchAll ()

Returns an array of arrays containing all the records in the result This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$robots = $result->fetchAll();

public int numRows ()

Gets number of rows returned by a resulset

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
echo 'There are ', $result->numRows(), ' rows in the resulset';

public dataSeek (int $number)

Moves internal resulset cursor to another position letting us to fetch a certain row

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$result->dataSeek(2); // Move to third row on result
$row = $result->fetch(); // Fetch third row

public setFetchMode (int $fetchMode)

Changes the fetching mode affecting Phalcon\Db\Result\Pdo::fetch()

<?php

//Return array with integer indexes
$result->setFetchMode(Phalcon\Db::FETCH_NUM);

//Return associative array without integer indexes
$result->setFetchMode(Phalcon\Db::FETCH_ASSOC);

//Return associative array together with integer indexes
$result->setFetchMode(Phalcon\Db::FETCH_BOTH);

//Return an object
$result->setFetchMode(Phalcon\Db::FETCH_OBJ);

public PDOStatement getInternalResult ()

Gets the internal PDO result object

Class Phalcon\Dispatcher

implements Phalcon\DispatcherInterface, Phalcon\DI\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

This is the base class for Phalcon\Mvc\Dispatcher and Phalcon\CLI\Dispatcher. This class can’t be instantiated directly, you can use it to create your own dispatchers

Constants

integer EXCEPTION_NO_DI

integer EXCEPTION_CYCLIC_ROUTING

integer EXCEPTION_HANDLER_NOT_FOUND

integer EXCEPTION_INVALID_HANDLER

integer EXCEPTION_INVALID_PARAMS

integer EXCEPTION_ACTION_NOT_FOUND

Methods

public __construct ()

Phalcon\Dispatcher constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the events manager

public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

public setActionSuffix (string $actionSuffix)

Sets the default action suffix

public setNamespaceName (string $namespaceName)

Sets a namespace to be prepended to the handler name

public string getNamespaceName ()

Gets a namespace to be prepended to the current handler name

public setDefaultNamespace (string $namespace)

Sets the default namespace

public string getDefaultNamespace ()

Returns the default namespace

public setDefaultAction (string $actionName)

Sets the default action name

public setActionName (string $actionName)

Sets the action name to be dispatched

public string getActionName ()

Gets last dispatched action name

public setParams (array $params)

Sets action params to be dispatched

public array getParams ()

Gets action params

public setParam (mixed $param, mixed $value)

Set a param by its name or numeric index

public mixed getParam (mixed $param, string|array $filters, mixed $defaultValue)

Gets a param by its name or numeric index

public boolean isFinished ()

Checks if the dispatch loop is finished or has more pendent controllers/tasks to disptach

public mixed getReturnedValue ()

Returns value returned by the lastest dispatched action

public object dispatch ()

Dispatches a handle action taking into account the routing parameters

public forward (array $forward)

Forwards the execution flow to another controller/action

Class Phalcon\Escaper

implements Phalcon\EscaperInterface

Escapes different kinds of text securing them. By using this component you may prevent XSS attacks. This component only works with UTF-8. The PREG extension needs to be compiled with UTF-8 support.

<?php

 $escaper = new Phalcon\Escaper();
 $escaped = $escaper->escapeCss("font-family: <Verdana>");
 echo $escaped; // font\2D family\3A \20 \3C Verdana\3E
Methods

public setEnconding (string $encoding)

Sets the encoding to be used by the escaper

public string getEncoding ()

Returns the internal encoding used by the escaper

public setHtmlQuoteType (int $quoteType)

Sets the HTML quoting type for htmlspecialchars

public string escapeHtml (string $text)

Escapes a HTML string. Internally uses htmlspeciarchars

public string escapeHtmlAttr (string $text)

Escapes a HTML attribute string

public string cssSanitize (array $matches)

Sanitizes CSS strings converting non-alphanumeric chars to their hexadecimal representation

public escapeCss (string $css)

Escape CSS strings by replacing non-alphanumeric chars by their hexadecimal representation

public string escapeUrl (string $url)

Escapes a URL. Internally uses rawurlencode

Class Phalcon\Escaper\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Events\Event

This class offers contextual information of a fired event in the EventsManager

Methods

public __construct (string $type, object $source, mixed $data, unknown $cancelable)

Phalcon\Events\Event constructor

public setType (string $eventType)

Set the event’s type

public string getType ()

Returns the event’s type

public object getSource ()

Returns the event’s source

public setData (string $data)

Set the event’s data

public mixed getData ()

Returns the event’s data

public setCancelable (boolean $cancelable)

Sets if the event is cancelable

public boolean getCancelable ()

Check whether the event is cancelable

public stop ()

Stops the event preventing propagation

public isStopped ()

Check whether the event is currently stopped

Class Phalcon\Events\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Events\Manager

implements Phalcon\Events\ManagerInterface

Phalcon Events Manager, offers an easy way to intercept and manipulate, if needed, the normal flow of operation. With the EventsManager the developer can create hooks or plugins that will offer monitoring of data, manipulation, conditional execution and much more.

Methods

public attach (string $eventType, object $handler)

Attach a listener to the events manager

public dettachAll (unknown $type)

Removes all events from the EventsManager

public mixed fire (string $eventType, object $source, mixed $data, int $cancelable)

Fires a event in the events manager causing that the acive listeners will be notified about it

public boolean hasListeners (string $type)

Check whether certain type of event has listeners

public array getListeners (string $type)

Returns all the attached listeners of a certain type

Class Phalcon\Exception

extends Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Filter

implements Phalcon\FilterInterface

The Phalcon\Filter component provides a set of commonly needed data filters. It provides object oriented wrappers to the php filter extension. Also allows the developer to define his/her own filters

<?php

$filter = new Phalcon\Filter();
$filter->sanitize("some(one)@exa\\mple.com", "email"); // returns "someone@example.com"
$filter->sanitize("hello<<", "string"); // returns "hello"
$filter->sanitize("!100a019", "int"); // returns "100019"
$filter->sanitize("!100a019.01a", "float"); // returns "100019.01"
Methods

public __construct ()

Phalcon\Filter constructor

public Phalcon\Filter add (string $name, callable $handler)

Adds a user-defined filter

public mixed sanitize (mixed $value, mixed $filters)

Sanizites a value with a specified single or set of filters

protected mixed _sanitize ()

Internal sanizite wrapper to filter_var

public object[] getFilters ()

Return the user-defined filters in the instance

Class Phalcon\Filter\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Flash

Shows HTML notifications related to different circumstances. Classes can be stylized using CSS

<?php

 $flash->success("The record was successfully deleted");
 $flash->error("Cannot open the file");
Methods

public __construct (array $cssClasses)

Phalcon\Flash constructor

public setImplicitFlush (unknown $implicitFlush)

Set the if the output must be implictly flushed to the output or returned as string

public setAutomaticHtml (boolean $automaticHtml)

Set the if the output must be implictly formatted with HTML

public setCssClasses (array $cssClasses)

Set an array with CSS classes to format the messages

public string error (string $message)

Shows a HTML error message

<?php

 $flash->error('This is an error');

public string notice (string $message)

Shows a HTML notice/information message

<?php

 $flash->notice('This is an information');

public string success (string $message)

Shows a HTML success message

<?php

 $flash->success('The process was finished successfully');

public string warning (string $message)

Shows a HTML warning message

<?php

 $flash->warning('Hey, this is important');

public outputMessage (string $type, string $message)

Outputs a message formatting it with HTML

Class Phalcon\Flash\Direct

extends Phalcon\Flash

implements Phalcon\FlashInterface

This is a variant of the Phalcon\Flash that inmediately outputs any message passed to it

Methods

public string message (string $type, string $message)

Outputs a message

public __construct (array $cssClasses) inherited from Phalcon\Flash

Phalcon\Flash constructor

public setImplicitFlush (unknown $implicitFlush) inherited from Phalcon\Flash

Set the if the output must be implictly flushed to the output or returned as string

public setAutomaticHtml (boolean $automaticHtml) inherited from Phalcon\Flash

Set the if the output must be implictly formatted with HTML

public setCssClasses (array $cssClasses) inherited from Phalcon\Flash

Set an array with CSS classes to format the messages

public string error (string $message) inherited from Phalcon\Flash

Shows a HTML error message

<?php

 $flash->error('This is an error');

public string notice (string $message) inherited from Phalcon\Flash

Shows a HTML notice/information message

<?php

 $flash->notice('This is an information');

public string success (string $message) inherited from Phalcon\Flash

Shows a HTML success message

<?php

 $flash->success('The process was finished successfully');

public string warning (string $message) inherited from Phalcon\Flash

Shows a HTML warning message

<?php

 $flash->warning('Hey, this is important');

public outputMessage (string $type, string $message) inherited from Phalcon\Flash

Outputs a message formatting it with HTML

Class Phalcon\Flash\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Flash\Session

extends Phalcon\Flash

implements Phalcon\FlashInterface, Phalcon\DI\InjectionAwareInterface

Temporarily stores the messages in session, then messages can be printed in the next request

Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

protected array _getSessionMessages ()

Returns the messages stored in session

protected _setSessionMessages ()

Stores the messages in session

public message (string $type, string $message)

Adds a message to the session flasher

public array getMessages (string $type, boolean $remove)

Returns the messages in the session flasher

public output (boolean $remove)

Prints the messages in the session flasher

public __construct (array $cssClasses) inherited from Phalcon\Flash

Phalcon\Flash constructor

public setImplicitFlush (unknown $implicitFlush) inherited from Phalcon\Flash

Set the if the output must be implictly flushed to the output or returned as string

public setAutomaticHtml (boolean $automaticHtml) inherited from Phalcon\Flash

Set the if the output must be implictly formatted with HTML

public setCssClasses (array $cssClasses) inherited from Phalcon\Flash

Set an array with CSS classes to format the messages

public string error (string $message) inherited from Phalcon\Flash

Shows a HTML error message

<?php

 $flash->error('This is an error');

public string notice (string $message) inherited from Phalcon\Flash

Shows a HTML notice/information message

<?php

 $flash->notice('This is an information');

public string success (string $message) inherited from Phalcon\Flash

Shows a HTML success message

<?php

 $flash->success('The process was finished successfully');

public string warning (string $message) inherited from Phalcon\Flash

Shows a HTML warning message

<?php

 $flash->warning('Hey, this is important');

public outputMessage (string $type, string $message) inherited from Phalcon\Flash

Outputs a message formatting it with HTML

Class Phalcon\Http\Request

implements Phalcon\Http\RequestInterface, Phalcon\DI\InjectionAwareInterface

Encapsulates request information for easy and secure access from application controllers. The request object is a simple value object that is passed between the dispatcher and controller classes. It packages the HTTP request environment.

<?php

$request = new Phalcon\Http\Request();
if ($request->isPost() == true) {
    if ($request->isAjax() == true) {
            echo 'Request was made using POST and AJAX';
    }
}
Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

public mixed get (string $name, string|array $filters, mixed $defaultValue)

Gets a variable from the $_REQUEST superglobal applying filters if needed

<?php

//Returns value from $_REQUEST["user_email"] without sanitizing
$userEmail = $request->get("user_email");

//Returns value from $_REQUEST["user_email"] with sanitizing
$userEmail = $request->get("user_email", "email");

public mixed getPost (string $name, string|array $filters, mixed $defaultValue)

Gets a variable from the $_POST superglobal applying filters if needed

<?php

//Returns value from $_POST["user_email"] without sanitizing
$userEmail = $request->getPost("user_email");

//Returns value from $_POST["user_email"] with sanitizing
$userEmail = $request->getPost("user_email", "email");

public mixed getQuery (string $name, string|array $filters, mixed $defaultValue)

Gets variable from $_GET superglobal applying filters if needed

<?php

//Returns value from $_GET["id"] without sanitizing
$id = $request->getQuery("id");

//Returns value from $_GET["id"] with sanitizing
$id = $request->getQuery("id", "int");

//Returns value from $_GET["id"] with a default value
$id = $request->getQuery("id", null, 150);

public mixed getServer (string $name)

Gets variable from $_SERVER superglobal

public boolean has (string $name)

Checks whether $_SERVER superglobal has certain index

public boolean hasPost (string $name)

Checks whether $_POST superglobal has certain index

public boolean hasQuery (string $name)

Checks whether $_SERVER superglobal has certain index

public mixed hasServer (string $name)

Checks whether $_SERVER superglobal has certain index

public string getHeader (string $header)

Gets HTTP header from request data

public string getScheme ()

Gets HTTP schema (http/https)

public boolean isAjax ()

Checks whether request has been made using ajax. Checks if $_SERVER[‘HTTP_X_REQUESTED_WITH’]==’XMLHttpRequest’

public boolean isSoapRequested ()

Checks whether request has been made using SOAP

public boolean isSecureRequest ()

Checks whether request has been made using any secure layer

public string getRawBody ()

Gets HTTP raws request body

public string getServerAddress ()

Gets active server address IP

public string getServerName ()

Gets active server name

public string getHttpHost ()

Gets information about schema, host and port used by the request

public string getClientAddress (boolean $trustForwardedHeader)

Gets most possibly client IPv4 Address. This methods search in $_SERVER[‘REMOTE_ADDR’] and optionally in $_SERVER[‘HTTP_X_FORWARDED_FOR’]

public string getMethod ()

Gets HTTP method which request has been made

public string getUserAgent ()

Gets HTTP user agent used to made the request

public boolean isMethod (string|array $methods)

Check if HTTP method match any of the passed methods

public boolean isPost ()

Checks whether HTTP method is POST. if $_SERVER[‘REQUEST_METHOD’]==’POST’

public boolean isGet ()

Checks whether HTTP method is GET. if $_SERVER[‘REQUEST_METHOD’]==’GET’

public boolean isPut ()

Checks whether HTTP method is PUT. if $_SERVER[‘REQUEST_METHOD’]==’PUT’

public boolean isHead ()

Checks whether HTTP method is HEAD. if $_SERVER[‘REQUEST_METHOD’]==’HEAD’

public boolean isDelete ()

Checks whether HTTP method is DELETE. if $_SERVER[‘REQUEST_METHOD’]==’DELETE’

public boolean isOptions ()

Checks whether HTTP method is OPTIONS. if $_SERVER[‘REQUEST_METHOD’]==’OPTIONS’

public boolean hasFiles ()

Checks whether request include attached files

public Phalcon\Http\Request\File [] getUploadedFiles ()

Gets attached files as Phalcon\Http\Request\File instances

public string getHTTPReferer ()

Gets web page that refers active request. ie: http://www.google.com

protected array _getQualityHeader ()

Process a request header and return an array of values with their qualities

protected string _getBestQuality ()

Process a request header and return the one with best quality

public array getAcceptableContent ()

Gets array with mime/types and their quality accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT’]

public array getBestAccept ()

Gets best mime/type accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT’]

public array getClientCharsets ()

Gets charsets array and their quality accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_CHARSET’]

public string getBestCharset ()

Gets best charset accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_CHARSET’]

public array getLanguages ()

Gets languages array and their quality accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_LANGUAGE’]

public string getBestLanguage ()

Gets best language accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_LANGUAGE’]

Class Phalcon\Http\Request\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Http\Request\File

implements Phalcon\Http\Request\FileInterface

Provides OO wrappers to the $_FILES superglobal

<?php

class PostsController extends \Phalcon\Mvc\Controller
{

public function uploadAction()
{
    //Check if the user has uploaded files
    if ($this->request->hasFiles() == true) {
            //Print the real file names and their sizes
            foreach ($this->request->getUploadedFiles() as $file){
                    echo $file->getName(), " ", $file->getSize(), "\n";
            }
    }
}

}
Methods

public __construct (array $file)

Phalcon\Http\Request\File constructor

public int getSize ()

Returns the file size of the uploaded file

public string getName ()

Returns the real name of the uploaded file

public string getTempName ()

Returns the temporal name of the uploaded file

public boolean moveTo (string $destination)

Move the temporary file to a destination

Class Phalcon\Http\Response

implements Phalcon\Http\ResponseInterface, Phalcon\DI\InjectionAwareInterface

Part of the HTTP cycle is return responses to the clients. Phalcon\HTTP\Response is the Phalcon component responsible to achieve this task. HTTP responses are usually composed by headers and body.

<?php

$response = new Phalcon\Http\Response();
$response->setStatusCode(200, "OK");
$response->setContent("<html><body>Hello</body></html>");
$response->send();
Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

public Phalcon\Http\ResponseInterface setStatusCode (int $code, string $message)

Sets the HTTP response code

<?php

$response->setStatusCode(404, "Not Found");

public Phalcon\Http\ResponseInterface setHeaders (Phalcon\Http\Response\HeadersInterface $headers)

Sets a headers bag for the response externally

public Phalcon\Http\Response\HeadersInterface getHeaders ()

Returns headers set by the user

public Phalcon\Http\ResponseInterface setCookies (Phalcon\Http\Response\CookiesInterface $cookies)

Sets a cookies bag for the response externally

public Phalcon\Http\Response\CookiesInterface getCookies ()

Returns coookies set by the user

public Phalcon\Http\ResponseInterface setHeader (string $name, string $value)

Overwrites a header in the response

<?php

$response->setHeader("Content-Type", "text/plain");

public Phalcon\Http\ResponseInterface setRawHeader (string $header)

Send a raw header to the response

<?php

$response->setRawHeader("HTTP/1.1 404 Not Found");

public Phalcon\Http\ResponseInterface resetHeaders ()

Resets all the stablished headers

public Phalcon\Http\ResponseInterface setExpires (DateTime $datetime)

Sets output expire time header

public Phalcon\Http\ResponseInterface setNotModified ()

Sends a Not-Modified response

public Phalcon\Http\ResponseInterface setContentType (string $contentType, string $charset)

Sets the response content-type mime, optionally the charset

<?php

$response->setContentType('application/pdf');
$response->setContentType('text/plain', 'UTF-8');

public Phalcon\Http\ResponseInterface redirect (string $location, boolean $externalRedirect, int $statusCode)

Redirect by HTTP to another action or URL

<?php

  //Using a string redirect (internal/external)
$response->redirect("posts/index");
$response->redirect("http://en.wikipedia.org", true);
$response->redirect("http://www.example.com/new-location", true, 301);

public Phalcon\Http\ResponseInterface setContent (string $content)

Sets HTTP response body

<?php

$response->setContent("<h1>Hello!</h1>");

public Phalcon\Http\ResponseInterface appendContent (string $content)

Appends a string to the HTTP response body

public string getContent ()

Gets the HTTP response body

public boolean isSent ()

Check if the response is already sent

public Phalcon\Http\ResponseInterface sendHeaders ()

Sends headers to the client

public Phalcon\Http\ResponseInterface send ()

Prints out HTTP response to the client

Class Phalcon\Http\Response\Cookies

implements Phalcon\DI\InjectionAwareInterface

This class is a bag to manage the cookies

Methods

public __construct ()

Phalcon\Http\Response\Cookies constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

public set (string $name, mixed $value, int $expire, string $path)

Sets a header to be sent at the end of the request

public Phalcon\Http\Cookie get (string $name)

Gets a cookie from the bag

public reset ()

Reset set cookies

Class Phalcon\Http\Response\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Http\Response\Headers

implements Phalcon\Http\Response\HeadersInterface

This class is a bag to manage the response headers

Methods

public __construct ()

Phalcon\Http\Response\Headers constructor

public set (string $name, string $value)

Sets a header to be sent at the end of the request

public string get (string $name)

Gets a header value from the internal bag

public setRaw (string $header)

Sets a raw header to be sent at the end of the request

public boolean send ()

Sends the headers to the client

public reset ()

Reset set headers

public static Phalcon\Http\Response\Headers __set_state (unknown $data)

Restore a Phalcon\Http\Response\Headers object

Class Phalcon\Loader

implements Phalcon\Events\EventsAwareInterface

This component helps to load your project classes automatically based on some conventions

<?php

 //Creates the autoloader
 $loader = new Phalcon\Loader();

 //Register some namespaces
 $loader->registerNamespaces(array(
   'Example\Base' => 'vendor/example/base/',
   'Example\Adapter' => 'vendor/example/adapter/',
   'Example' => 'vendor/example/'
 ));

 //register autoloader
 $loader->register();

 //Requiring this class will automatically include file vendor/example/adapter/Some.php
 $adapter = Example\Adapter\Some();
Methods

public __construct ()

Phalcon\Loader constructor

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the events manager

public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

public Phalcon\Loader setExtensions (array $extensions)

Sets an array of extensions that the Loader must check together with the path

public boolean getExtensions ()

Return file extensions registered in the loader

public Phalcon\Loader registerNamespaces (array $namespaces, boolean $merge)

Register namespaces and their related directories

public getNamespaces ()

Return current namespaces registered in the autoloader

public Phalcon\Loader registerPrefixes (unknown $prefixes, boolean $merge)

Register directories on which “not found” classes could be found

public getPrefixes ()

Return current prefixes registered in the autoloader

public Phalcon\Loader registerDirs (array $directories, boolean $merge)

Register directories on which “not found” classes could be found

public getDirs ()

Return current directories registered in the autoloader

public Phalcon\Loader registerClasses (array $classes, boolean $merge)

Register classes and their locations

public getClasses ()

Return the current class-map registered in the autoloader

public Phalcon\Loader register ()

Register the autoload method

public Phalcon\Loader unregister ()

Unregister the autoload method

public boolean autoLoad (string $className)

Makes the work of autoload registered classes

public string getFoundPath ()

Get the path when a class was found

public string getCheckedPath ()

Get the path the loader is checking for a path

Class Phalcon\Loader\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Logger

Constants

integer SPECIAL

integer CUSTOM

integer DEBUG

integer INFO

integer NOTICE

integer WARNING

integer ERROR

integer ALERT

integer CRITICAL

integer EMERGENCE

Class Phalcon\Logger\Adapter

Base class for Phalcon\Logger adapters

Methods

public string getTypeString (integer $type)

Returns the string meaning of a logger constant

public debug (string $message)

Sends/Writes a debug message to the log

public error (string $message)

Sends/Writes an error message to the log

public info (string $message)

Sends/Writes an info message to the log

public notice (string $message)

Sends/Writes a notice message to the log

public warning (string $message)

Sends/Writes a warning message to the log

public alert (string $message)

Sends/Writes an alert message to the log

public log (string $message, int $type)

Logs a message

Class Phalcon\Logger\Adapter\File

extends Phalcon\Logger\Adapter

implements Phalcon\Logger\AdapterInterface

Adapter to store logs in plain text files

<?php

$logger = new Phalcon\Logger\Adapter\File("app/logs/test.log");
$logger->log("This is a message");
$logger->log("This is an error", Phalcon\Logger::ERROR);
$logger->error("This is another error");
$logger->close();
Methods

public __construct (string $name, array $options)

Phalcon\Logger\Adapter\File constructor

public setFormat (string $format)

Set the log format

public format getFormat ()

Returns the log format

protected string _applyFormat ()

Applies the internal format to the message

public setDateFormat (string $date)

Sets the internal date format

public string getDateFormat ()

Returns the internal date format

public log (string $message, int $type)

Sends/Writes messages to the file log

public begin ()

Starts a transaction

public commit ()

Commits the internal transaction

public rollback ()

Rollbacks the internal transaction

public boolean close ()

Closes the logger

public __wakeup ()

Opens the internal file handler after unserialization

public string getTypeString (integer $type) inherited from Phalcon\Logger\Adapter

Returns the string meaning of a logger constant

public debug (string $message) inherited from Phalcon\Logger\Adapter

Sends/Writes a debug message to the log

public error (string $message) inherited from Phalcon\Logger\Adapter

Sends/Writes an error message to the log

public info (string $message) inherited from Phalcon\Logger\Adapter

Sends/Writes an info message to the log

public notice (string $message) inherited from Phalcon\Logger\Adapter

Sends/Writes a notice message to the log

public warning (string $message) inherited from Phalcon\Logger\Adapter

Sends/Writes a warning message to the log

public alert (string $message) inherited from Phalcon\Logger\Adapter

Sends/Writes an alert message to the log

Class Phalcon\Logger\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Logger\Item

Represents each item in a logging transaction

Methods

public __construct (string $message, integer $type, integer $time)

Phalcon\Logger\Item constructor

public string getMessage ()

Returns the message

public integer getType ()

Returns the log type

public integer getTime ()

Returns log timestamp

Class Phalcon\Mvc\Application

extends Phalcon\DI\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface

This component encapsulates all the complex operations behind instantiating every component needed and integrating it with the rest to allow the MVC pattern to operate as desired.

<?php

 class Application extends \Phalcon\Mvc\Application
 {

    /**
     * Register the services here to make them general or register in the ModuleDefinition to make them module-specific
     *\/
    protected function _registerServices()
    {

    }

    /**
     * This method execute the right module
     *\/
    public function main()
    {
            $this->registerModules(array(
                    'frontend' => array(
                            'className' => 'Multiple\Frontend\Module',
                            'path' => '../apps/frontend/Module.php'
                    ),
                    'backend' => array(
                            'className' => 'Multiple\Backend\Module',
                            'path' => '../apps/backend/Module.php'
                    )
            ));
    }
}

$application = new Application();
$application->main();
Methods

public registerModules (array $modules, boolean $merge)

Register an array of modules present in the application

<?php

$this->registerModules(array(
    'frontend' => array(
            'className' => 'Multiple\Frontend\Module',
            'path' => '../apps/frontend/Module.php'
    ),
    'backend' => array(
            'className' => 'Multiple\Backend\Module',
            'path' => '../apps/backend/Module.php'
    )
));

public array getModules ()

Return the modules registered in the application

public Phalcon\Http\ResponseInterface handle ()

Handles a MVC request

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI\Injectable

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\Application\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Collection

implements Phalcon\DI\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

This component implements a high level abstraction for NoSQL databases which works with documents

Constants

integer OP_NONE

integer OP_CREATE

integer OP_UPDATE

integer OP_DELETE

Methods

public __construct (Phalcon\DiInterface $dependencyInjector)

public setId (mixed $id)

Sets a value for the _id propery, creates a MongoId object if needed

public MongoId getId ()

Returns the value of the _id property

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public Phalcon\DiInterface getDI ()

Returns the dependency injection container

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

public array getReservedAttributes ()

Returns an array with reserved properties that cannot be part of the insert/update

protected Phalcon\Mvc\Collection setSource ()

Sets collection name which model should be mapped

public string getSource ()

Returns collection name mapped in the model

public setConnectionService (string $connectionService)

Sets a service in the services container that returns the Mongo database

public MongoDb getConnection ()

Retrieves a database connection

public mixed readAttribute (string $attribute)

Reads an attribute value by its name <code> echo $robot->readAttribute(‘name’);

public writeAttribute (string $attribute, mixed $value)

Writes an attribute value by its name <code>$robot->writeAttribute(‘name’, ‘Rosey’);

protected static Phalcon\Mvc\Collection dumpResult ()

Returns a cloned collection

protected static array _getResultset ()

Returns a collection resultset

protected boolean _preSave ()

Executes internal hooks before save a document

protected boolean _postSave ()

Executes internal events after save a document

protected validate ()

Executes validators on every validation call

<?php

use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;

class Subscriptors extends Phalcon\Mvc\Collection
{

public function validation()
  {
            $this->validate(new ExclusionIn(array(
            'field' => 'status',
            'domain' => array('A', 'I')
    )));
    if ($this->validationHasFailed() == true) {
            return false;
    }
}

}

public boolean validationHasFailed ()

Check whether validation process has generated any messages

<?php

use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;

class Subscriptors extends Phalcon\Mvc\Model
{

public function validation()
  {
            $this->validate(new ExclusionIn(array(
            'field' => 'status',
            'domain' => array('A', 'I')
    )));
    if ($this->validationHasFailed() == true) {
            return false;
    }
}

}

protected boolean _callEvent ()

Fires an internal event

protected boolean _callEventCancel ()

Fires an internal event that cancels the operation

protected boolean _cancelOperation ()

Cancel the current operation

protected _exists ()

Checks if the document exists in the collection

public save ()

public static Phalcon\Mvc\Collection findById (string $id)

Find a document by its id

public static array findFirst (array $parameters)

Allows to query the first record that match the specified conditions

<?php

 //What's the first robot in robots table?
 $robot = Robots::findFirst();
 echo "The robot name is ", $robot->name;

 //What's the first mechanical robot in robots table?
 $robot = Robots::findFirst(array(
     array("type" => "mechanical")
 ));
 echo "The first mechanical robot name is ", $robot->name;

 //Get first virtual robot ordered by name
 $robot = Robots::findFirst(array(
     array("type" => "mechanical"),
     "order" => array("name" => 1)
 ));
 echo "The first virtual robot name is ", $robot->name;

public static array find (array $parameters)

Allows to query a set of records that match the specified conditions

<?php

 //How many robots are there?
 $robots = Robots::find();
 echo "There are ", count($robots);

 //How many mechanical robots are there?
 $robots = Robots::find(array(
     array("type" => "mechanical")
 ));
 echo "There are ", count($robots);

 //Get and print virtual robots ordered by name
 $robots = Robots::findFirst(array(
     array("type" => "virtual"),
     "order" => array("name" => 1)
 ));
 foreach ($robots as $robot) {
   echo $robot->name, "\n";
 }

 //Get first 100 virtual robots ordered by name
 $robots = Robots::find(array(
     array("type" => "virtual"),
     "order" => array("name" => 1),
     "limit" => 100
 ));
 foreach ($robots as $robot) {
   echo $robot->name, "\n";
 }

public static count (unknown $parameters)

public boolean delete ()

Deletes a model instance. Returning true on success or false otherwise.

<?php

$robot = Robots::findFirst();
$robot->delete();

foreach(Robots::find() as $robot){
   $robot->delete();
}

Class Phalcon\Mvc\Collection\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Collection\Manager

This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\DI.

<?php

 $dependencyInjector = new Phalcon\DI();

 $dependencyInjector->set('collectionManager', function(){
      return new Phalcon\Mvc\Collection\Manager();
 });

 $robot = new Robots($dependencyInjector);
Methods

public __construct ()

Phalcon\Mvc\Collection\Manager constructor

public isInitialized (unknown $collection)

...

public initialize ()

...

Class Phalcon\Mvc\Controller

extends Phalcon\DI\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface

Every application controller should extend this class that encapsulates all the controller functionality The controllers provide the “flow” between models and views. Controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.

<?php

class PeopleController extends \Phalcon\Mvc\Controller
{

  //This action will be executed by default
  public function indexAction()
  {

  }

  public function findAction()
  {

  }

  public function saveAction()
  {
   //Forwards flow to the index action
   return $this->dispatcher->forward(array('controller' => 'people', 'action' => 'index'));
  }

  //This action will be executed when a non existent action is requested
  public function notFoundAction()
  {

  }

}
Methods

final public __construct ()

Phalcon\Mvc\Controller constructor

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI\Injectable

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\Dispatcher

extends Phalcon\Dispatcher

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface, Phalcon\DispatcherInterface, Phalcon\Mvc\DispatcherInterface

Dispatching is the process of taking the request object, extracting the module name, controller name, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller.

<?php

$di = new Phalcon\DI();

$dispatcher = new Phalcon\Mvc\Dispatcher();

  $dispatcher->setDI($di);

$dispatcher->setControllerName('posts');
$dispatcher->setActionName('index');
$dispatcher->setParams(array());

$controller = $dispatcher->dispatch();
Constants

integer EXCEPTION_NO_DI

integer EXCEPTION_CYCLIC_ROUTING

integer EXCEPTION_HANDLER_NOT_FOUND

integer EXCEPTION_INVALID_HANDLER

integer EXCEPTION_INVALID_PARAMS

integer EXCEPTION_ACTION_NOT_FOUND

Methods

public setControllerSuffix (string $controllerSuffix)

Sets the default controller suffix

public setDefaultController (string $controllerName)

Sets the default controller name

public setControllerName (string $controllerName)

Sets the controller name to be dispatched

public string getControllerName ()

Gets last dispatched controller name

protected _throwDispatchException ()

Throws an internal exception

public Phalcon\Mvc\Controller getLastController ()

Returns the lastest dispatched controller

public Phalcon\Mvc\Controller getActiveController ()

Returns the active controller in the dispatcher

public __construct () inherited from Phalcon\Dispatcher

Phalcon\Dispatcher constructor

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Dispatcher

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\Dispatcher

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Dispatcher

Sets the events manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\Dispatcher

Returns the internal event manager

public setActionSuffix (string $actionSuffix) inherited from Phalcon\Dispatcher

Sets the default action suffix

public setNamespaceName (string $namespaceName) inherited from Phalcon\Dispatcher

Sets a namespace to be prepended to the handler name

public string getNamespaceName () inherited from Phalcon\Dispatcher

Gets a namespace to be prepended to the current handler name

public setDefaultNamespace (string $namespace) inherited from Phalcon\Dispatcher

Sets the default namespace

public string getDefaultNamespace () inherited from Phalcon\Dispatcher

Returns the default namespace

public setDefaultAction (string $actionName) inherited from Phalcon\Dispatcher

Sets the default action name

public setActionName (string $actionName) inherited from Phalcon\Dispatcher

Sets the action name to be dispatched

public string getActionName () inherited from Phalcon\Dispatcher

Gets last dispatched action name

public setParams (array $params) inherited from Phalcon\Dispatcher

Sets action params to be dispatched

public array getParams () inherited from Phalcon\Dispatcher

Gets action params

public setParam (mixed $param, mixed $value) inherited from Phalcon\Dispatcher

Set a param by its name or numeric index

public mixed getParam (mixed $param, string|array $filters, mixed $defaultValue) inherited from Phalcon\Dispatcher

Gets a param by its name or numeric index

public boolean isFinished () inherited from Phalcon\Dispatcher

Checks if the dispatch loop is finished or has more pendent controllers/tasks to disptach

public mixed getReturnedValue () inherited from Phalcon\Dispatcher

Returns value returned by the lastest dispatched action

public object dispatch () inherited from Phalcon\Dispatcher

Dispatches a handle action taking into account the routing parameters

public forward (array $forward) inherited from Phalcon\Dispatcher

Forwards the execution flow to another controller/action

Class Phalcon\Mvc\Dispatcher\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Micro

extends Phalcon\DI\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface

With Phalcon you can create “Micro-Framework like” applications. By doing this, you only need to write a minimal amount of code to create a PHP application. Micro applications are suitable to small applications, APIs and prototypes in a practical way.

<?php

 $app = new Phalcon\Mvc\Micro();

 $app->get('/say/welcome/{name}', function ($name) {
    echo "<h1>Welcome $name!</h1>";
 });

 $app->handle();
Methods

public __construct ()

Phalcon\Mvc\Micro constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public map (string $routePattern, callable $handler)

Maps a route to a handler without any HTTP method constraint

public get (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is GET

public post (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is POST

public put (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is PUT

public head (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is HEAD

public delete (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is DELETE

public options (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is GET

public notFound (callable $handler)

Sets a handler that will be called when the router doesn’t match any of the defined routes

public Phalcon\Mvc\RouterInterface getRouter ()

Returns the internal router used by the application

public object getService (unknown $serviceName)

Obtains a service from the DI

public getSharedService (unknown $serviceName)

Obtains a shared service from the DI

public mixed handle (string $uri)

Handle the whole request

public setActiveHandler (callable $activeHandler)

Sets externally the handler that must be called by the matched route

public callable getActiveHandler ()

Return the handler that will be called for the matched route

public mixed getReturnedValue ()

Returns the value returned by the executed handler

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\Micro\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Model

implements Phalcon\Mvc\ModelInterface, Phalcon\Mvc\Model\ResultInterface, Phalcon\DI\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface, Serializable

Phalcon\Mvc\Model connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It‘s an implementation of the object-relational mapping (ORM). A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models. Phalcon\Mvc\Model is the first ORM written in C-language for PHP, giving to developers high performance when interacting with databases while is also easy to use.

<?php

 $robot = new Robots();
 $robot->type = 'mechanical'
 $robot->name = 'Astro Boy';
 $robot->year = 1952;
 if ($robot->save() == false) {
  echo "Umh, We can store robots: ";
  foreach ($robot->getMessages() as $message) {
    echo $message;
  }
 } else {
  echo "Great, a new robot was saved successfully!";
 }
Constants

integer OP_NONE

integer OP_CREATE

integer OP_UPDATE

integer OP_DELETE

Methods

final public __construct (Phalcon\DiInterface $dependencyInjector, string $managerService, string $dbService)

Phalcon\Mvc\Model constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public Phalcon\DiInterface getDI ()

Returns the dependency injection container

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

public Phalcon\Mvc\Model setTransaction (Phalcon\Mvc\Model\TransactionInterface $transaction)

Sets a transaction related to the Model instance

<?php

try {

  $transactionManager = new Phalcon\Mvc\Model\Transaction\Manager();

  $transaction = $transactionManager->get();

  $robot = new Robots();
  $robot->setTransaction($transaction);
  $robot->name = 'WALL·E';
  $robot->created_at = date('Y-m-d');
  if($robot->save()==false){
    $transaction->rollback("Can't save robot");
  }

  $robotPart = new RobotParts();
  $robotPart->setTransaction($transaction);
  $robotPart->type = 'head';
  if ($robotPart->save() == false) {
    $transaction->rollback("Can't save robot part");
  }

  $transaction->commit();

}
catch(Phalcon\Mvc\Model\Transaction\Failed $e){
  echo 'Failed, reason: ', $e->getMessage();
}

protected Phalcon\Mvc\Model setSource ()

Sets table name which model should be mapped

public string getSource ()

Returns table name mapped in the model

protected Phalcon\Mvc\Model setSchema ()

Sets schema name where table mapped is located

public string getSchema ()

Returns schema name where table mapped is located

public Phalcon\Mvc\Model setConnectionService (string $connectionService)

Sets the DependencyInjection connection service

public string getConnectionService ()

Returns DependencyInjection connection service

public setForceExists (boolean $forceExists)

Forces that model doesn’t need to be checked if exists before store it

public Phalcon\Db\AdapterInterface getConnection ()

Gets the internal database connection

public static Phalcon\Mvc\Model $result dumpResultMap (Phalcon\Mvc\Model $base, array $data, array $columnMap, boolean $forceExists)

Assigns values to a model from an array returning a new model.

<?php

$robot = Phalcon\Mvc\Model::dumpResult(new Robots(), array(
  'type' => 'mechanical',
  'name' => 'Astro Boy',
  'year' => 1952
));

public static Phalcon\Mvc\Model $result dumpResult (Phalcon\Mvc\Model $base, array $data, boolean $forceExists)

Assigns values to a model from an array returning a new model.

<?php

$robot = Phalcon\Mvc\Model::dumpResult(new Robots(), array(
  'type' => 'mechanical',
  'name' => 'Astro Boy',
  'year' => 1952
));

public static Phalcon\Mvc\Model\ResultsetInterface find (array $parameters)

Allows to query a set of records that match the specified conditions

<?php

 //How many robots are there?
 $robots = Robots::find();
 echo "There are ", count($robots);

 //How many mechanical robots are there?
 $robots = Robots::find("type='mechanical'");
 echo "There are ", count($robots);

 //Get and print virtual robots ordered by name
 $robots = Robots::find(array("type='virtual'", "order" => "name"));
 foreach ($robots as $robot) {
   echo $robot->name, "\n";
 }

 //Get first 100 virtual robots ordered by name
 $robots = Robots::find(array("type='virtual'", "order" => "name", "limit" => 100));
 foreach ($robots as $robot) {
   echo $robot->name, "\n";
 }

public static Phalcon\Mvc\Model findFirst (array $parameters)

Allows to query the first record that match the specified conditions

<?php

 //What's the first robot in robots table?
 $robot = Robots::findFirst();
 echo "The robot name is ", $robot->name;

 //What's the first mechanical robot in robots table?
 $robot = Robots::findFirst("type='mechanical'");
 echo "The first mechanical robot name is ", $robot->name;

 //Get first virtual robot ordered by name
 $robot = Robots::findFirst(array("type='virtual'", "order" => "name"));
 echo "The first virtual robot name is ", $robot->name;

public static Phalcon\Mvc\Model\Criteria query (unknown $dependencyInjector)

Create a criteria for a especific model

protected boolean _exists ()

Checks if the current record already exists or not

protected static Phalcon\Mvc\Model\ResultsetInterface _groupResult ()

Generate a PHQL SELECT statement for an aggregate

public static int count (array $parameters)

Allows to count how many records match the specified conditions

<?php

 //How many robots are there?
 $number = Robots::count();
 echo "There are ", $number;

 //How many mechanical robots are there?
 $number = Robots::count("type='mechanical'");
 echo "There are ", $number, " mechanical robots";

public static double sum (array $parameters)

Allows to calculate a summatory on a column that match the specified conditions

<?php

 //How much are all robots?
 $sum = Robots::sum(array('column' => 'price'));
 echo "The total price of robots is ", $sum;

 //How much are mechanical robots?
 $sum = Robots::sum(array("type='mechanical'", 'column' => 'price'));
 echo "The total price of mechanical robots is  ", $sum;

public static mixed maximum (array $parameters)

Allows to get the maximum value of a column that match the specified conditions

<?php

 //What is the maximum robot id?
 $id = Robots::maximum(array('column' => 'id'));
 echo "The maximum robot id is: ", $id;

 //What is the maximum id of mechanical robots?
 $sum = Robots::maximum(array("type='mechanical'", 'column' => 'id'));
 echo "The maximum robot id of mechanical robots is ", $id;

public static mixed minimum (array $parameters)

Allows to get the minimum value of a column that match the specified conditions

<?php

 //What is the minimum robot id?
 $id = Robots::minimum(array('column' => 'id'));
 echo "The minimum robot id is: ", $id;

 //What is the minimum id of mechanical robots?
 $sum = Robots::minimum(array("type='mechanical'", 'column' => 'id'));
 echo "The minimum robot id of mechanical robots is ", $id;

public static double average (array $parameters)

Allows to calculate the average value on a column matching the specified conditions

<?php

 //What's the average price of robots?
 $average = Robots::average(array('column' => 'price'));
 echo "The average price is ", $average;

 //What's the average price of mechanical robots?
 $average = Robots::average(array("type='mechanical'", 'column' => 'price'));
 echo "The average price of mechanical robots is ", $average;

protected boolean _callEvent ()

Fires an internal event

protected boolean _callEventCancel ()

Fires an internal event that cancels the operation

protected boolean _cancelOperation ()

Cancel the current operation

public appendMessage (Phalcon\Mvc\Model\MessageInterface $message)

Appends a customized message on the validation process

<?php

 use \Phalcon\Mvc\Model\Message as Message;

 class Robots extends Phalcon\Mvc\Model
 {

   public function beforeSave()
   {
     if (this->name == 'Peter') {
        $message = new Message("Sorry, but a robot cannot be named Peter");
        $this->appendMessage($message);
     }
   }
 }

protected validate ()

Executes validators on every validation call

<?php

use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;

class Subscriptors extends Phalcon\Mvc\Model
{

public function validation()
  {
            $this->validate(new ExclusionIn(array(
            'field' => 'status',
            'domain' => array('A', 'I')
    )));
    if ($this->validationHasFailed() == true) {
            return false;
    }
}

}

public boolean validationHasFailed ()

Check whether validation process has generated any messages

<?php

use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;

class Subscriptors extends Phalcon\Mvc\Model
{

public function validation()
  {
            $this->validate(new ExclusionIn(array(
            'field' => 'status',
            'domain' => array('A', 'I')
    )));
    if ($this->validationHasFailed() == true) {
            return false;
    }
}

}

public Phalcon\Mvc\Model\MessageInterface [] getMessages ()

Returns all the validation messages

<?php

$robot = new Robots();
$robot->type = 'mechanical';
$robot->name = 'Astro Boy';
$robot->year = 1952;
if ($robot->save() == false) {
  echo "Umh, We can't store robots right now ";
  foreach ($robot->getMessages() as $message) {
    echo $message;
  }
} else {
  echo "Great, a new robot was saved successfully!";
}

protected boolean _checkForeignKeys ()

Reads “belongs to” relations and check the virtual foreign keys when inserting or updating records

protected boolean _checkForeignKeysReverse ()

Reads both “hasMany” and “hasOne” relations and check the virtual foreign keys when deleting records

protected boolean _preSave ()

Executes internal hooks before save a record

protected boolean _postSave ()

Executes internal events after save a record

protected boolean _doLowInsert ()

Sends a pre-build INSERT SQL statement to the relational database system

protected boolean _doLowUpdate ()

Sends a pre-build UPDATE SQL statement to the relational database system

public boolean save (array $data)

Inserts or updates a model instance. Returning true on success or false otherwise.

<?php

//Creating a new robot
$robot = new Robots();
$robot->type = 'mechanical'
$robot->name = 'Astro Boy';
$robot->year = 1952;
$robot->save();

//Updating a robot name
$robot = Robots::findFirst("id=100");
$robot->name = "Biomass";
$robot->save();

public boolean create (array $data)

Inserts a model instance. If the instance already exists in the persistance it will throw an exception Returning true on success or false otherwise.

<?php

//Creating a new robot
$robot = new Robots();
$robot->type = 'mechanical'
$robot->name = 'Astro Boy';
$robot->year = 1952;
$robot->create();

  //Passing an array to create
  $robot = new Robots();
  $robot->create(array(
      'type' => 'mechanical',
      'name' => 'Astroy Boy',
      'year' => 1952
  ));

public boolean update (array $data)

Updates a model instance. If the instance doesn’t exist in the persistance it will throw an exception Returning true on success or false otherwise.

<?php

//Updating a robot name
$robot = Robots::findFirst("id=100");
$robot->name = "Biomass";
$robot->update();

public boolean delete ()

Deletes a model instance. Returning true on success or false otherwise.

<?php

$robot = Robots::findFirst("id=100");
$robot->delete();

foreach(Robots::find("type = 'mechanical'") as $robot){
   $robot->delete();
}

public int getOperationMade ()

Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants

public mixed readAttribute (string $attribute)

Reads an attribute value by its name

<?php

 echo $robot->readAttribute('name');

public writeAttribute (string $attribute, mixed $value)

Writes an attribute value by its name

<?php

 $robot->writeAttribute('name', 'Rosey');

protected skipAttributes ()

Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
       $this->skipAttributes(array('price'));
   }

}

protected skipAttributesOnCreate ()

Sets a list of attributes that must be skipped from the generated INSERT statement

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
       $this->skipAttributesOnUpdate(array('created_at'));
   }

}

protected skipAttributesOnUpdate ()

Sets a list of attributes that must be skipped from the generated UPDATE statement

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
       $this->skipAttributesOnUpdate(array('modified_in'));
   }

}

protected hasOne ()

Setup a 1-1 relation between two models

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
       $this->hasOne('id', 'RobotsDescription', 'robots_id');
   }

}

protected belongsTo ()

Setup a relation reverse 1-1 between two models

<?php

class RobotsParts extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
       $this->belongsTo('robots_id', 'Robots', 'id');
   }

}

protected hasMany ()

Setup a relation 1-n between two models

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
       $this->hasMany('id', 'RobotsParts', 'robots_id');
   }

}

public Phalcon\Mvc\Model\ResultsetInterface getRelated (string $modelName, array $arguments)

Returns related records based on defined relations

protected mixed __getRelatedRecords ()

Returns related records defined relations depending on the method name

public mixed __call (string $method, array $arguments)

Handles methods when a method does not exist

public string serialize ()

Serializes the object ignoring connections or static properties

public unserialize (string $data)

Unserializes the object from a serialized string

public dump ()

...

Class Phalcon\Mvc\Model\Criteria

implements Phalcon\Mvc\Model\CriteriaInterface, Phalcon\DI\InjectionAwareInterface

This class allows to build the array parameter required by Phalcon\Mvc\Model::find and Phalcon\Mvc\Model::findFirst, using an object-oriented interfase

Methods

public __construct ()

Phalcon\Mvc\Model\Criteria constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public Phalcon\DiInterface getDI ()

Returns the DependencyInjector container

public Phalcon\Mvc\Model\Criteria setModelName (string $modelName)

Set a model on which the query will be executed

public string getModelName ()

Returns an internal model name on which the criteria will be applied

public Phalcon\Mvc\Model\Criteria bind (string $bindParams)

Adds the bind parameter to the criteria

public Phalcon\Mvc\Model\Criteria where (string $conditions)

Adds the conditions parameter to the criteria

public Phalcon\Mvc\Model\Criteria conditions (string $conditions)

Adds the conditions parameter to the criteria

public Phalcon\Mvc\Model\Criteria order (string $orderColumns)

Adds the order-by parameter to the criteria

public Phalcon\Mvc\Model\Criteria limit (int $limit, int $offset)

Adds the limit parameter to the criteria

public Phalcon\Mvc\Model\Criteria forUpdate (boolean $forUpdate)

Adds the “for_update” parameter to the criteria

public Phalcon\Mvc\Model\Criteria sharedLock (boolean $sharedLock)

Adds the “shared_lock” parameter to the criteria

public string getWhere ()

Returns the conditions parameter in the criteria

public string getConditions ()

Returns the conditions parameter in the criteria

public string getLimit ()

Returns the limit parameter in the criteria

public string getOrder ()

Returns the order parameter in the criteria

public string getParams ()

Returns all the parameters defined in the criteria

public static fromInput (Phalcon\DiInterface $dependencyInjector, string $modelName, array $data)

Builds a Phalcon\Mvc\Model\Criteria based on an input array like $_POST

public Phalcon\Mvc\Model\ResultsetInterface execute ()

Executes a find using the parameters built with the criteria

Class Phalcon\Mvc\Model\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Model\Manager

implements Phalcon\Mvc\Model\ManagerInterface, Phalcon\DI\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

This components controls the initialization of models, keeping record of relations between the different models of the application. A ModelsManager is injected to a model via a Dependency Injector Container such as Phalcon\DI.

<?php

 $dependencyInjector = new Phalcon\DI();

 $dependencyInjector->set('modelsManager', function(){
      return new Phalcon\Mvc\Model\Manager();
 });

 $robot = new Robots($dependencyInjector);
Methods

public __construct ()

Phalcon\Mvc\Model\Manager constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public Phalcon\DiInterface getDI ()

Returns the DependencyInjector container

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

public initialize (Phalcon\Mvc\ModelInterface $model)

Initializes a model in the model manager

public bool isInitialized (string $modelName)

Check of a model is already initialized

public Phalcon\Mvc\ModelInterface getLastInitialized ()

Get last initialized model

public Phalcon\Mvc\ModelInterface load (unknown $modelName)

Loads a model throwing an exception if it doesn’t exist

public addHasOne (Phalcon\Mvc\Model $model, mixed $fields, string $referenceModel, mixed $referencedFields, array $options)

Setup a 1-1 relation between two models

public addBelongsTo (Phalcon\Mvc\Model $model, mixed $fields, string $referenceModel, mixed $referencedFields, array $options)

Setup a relation reverse 1-1 between two models

public addHasMany (Phalcon\Mvc\ModelInterface $model, mixed $fields, string $referenceModel, mixed $referencedFields, array $options)

Setup a relation 1-n between two models

public boolean existsBelongsTo (string $modelName, string $modelRelation)

Checks whether a model has a belongsTo relation with another model

public boolean existsHasMany (string $modelName, string $modelRelation)

Checks whether a model has a hasMany relation with another model

public boolean existsHasOne (string $modelName, string $modelRelation)

Checks whether a model has a hasOne relation with another model

protected Phalcon\Mvc\Model\Resultset\Simple _getRelationRecords ()

Helper method to query records based on a relation definition

public Phalcon\Mvc\Model\ResultsetInterface getBelongsToRecords (string $method, string $modelName, string $modelRelation, Phalcon\Mvc\Model $record, array $parameters)

Gets belongsTo related records from a model

public Phalcon\Mvc\Model\ResultsetInterface getHasManyRecords (string $method, string $modelName, string $modelRelation, Phalcon\Mvc\Model $record, array $parameters)

Gets hasMany related records from a model

public Phalcon\Mvc\Model\ResultsetInterface getHasOneRecords (string $method, string $modelName, string $modelRelation, Phalcon\Mvc\Model $record, array $parameters)

Gets belongsTo related records from a model

public array getBelongsTo (Phalcon\Mvc\ModelInterface $model)

Gets belongsTo relations defined on a model

public array getHasMany (Phalcon\Mvc\ModelInterface $model)

Gets hasMany relations defined on a model

public array getHasOne (Phalcon\Mvc\ModelInterface $model)

Gets hasOne relations defined on a model

public array getHasOneAndHasMany (Phalcon\Mvc\ModelInterface $model)

Gets hasOne relations defined on a model

public array getRelations (string $first, string $second)

Query the relationships between two models

public Phalcon\Mvc\Model\Query createQuery (string $phql)

Creates a Phalcon\Mvc\Model\Query without execute it

public Phalcon\Mvc\Model\Query executeQuery (string $phql, array $placeholders)

Creates a Phalcon\Mvc\Model\Query and execute it

public Phalcon\Mvc\Model\Query\Builder createBuilder (string $params)

Creates a Phalcon\Mvc\Model\Query\Builder

Class Phalcon\Mvc\Model\Message

implements Phalcon\Mvc\Model\MessageInterface

Encapsulates validation info generated before save/delete records fails

<?php

 use Phalcon\Mvc\Model\Message as Message;

 class Robots extends Phalcon\Mvc\Model
{

   public function beforeSave()
   {
     if (this->name == 'Peter') {
        $text = "A robot cannot be named Peter";
        $field = "name";
        $type = "InvalidValue";
        $message = new Message($text, $field, $type);
        $this->appendMessage($message);
     }
   }

 }
Methods

public __construct (string $message, string $field, string $type)

Phalcon\Mvc\Model\Message constructor

public Phalcon\Mvc\Model\Message setType (string $type)

Sets message type

public string getType ()

Returns message type

public Phalcon\Mvc\Model\Message setMessage (string $message)

Sets verbose message

public string getMessage ()

Returns verbose message

public Phalcon\Mvc\Model\Message setField (string $field)

Sets field name related to message

public string getField ()

Returns field name related to message

public string __toString ()

Magic __toString method returns verbose message

public static Phalcon\Mvc\Model\Message __set_state (array $message)

Magic __set_state helps to recover messsages from serialization

Class Phalcon\Mvc\Model\MetaData

Because Phalcon\Mvc\Model requires meta-data like field names, data types, primary keys, etc. this component collect them and store for further querying by Phalcon\Model\Base. Phalcon\Mvc\Model\MetaData can also use adapters to store temporarily or permanently the meta-data. A standard Phalcon\Mvc\Model\MetaData can be used to query model attributes:

<?php

$metaData = new Phalcon\Mvc\Model\MetaData\Memory();
$attributes = $metaData->getAttributes(new Robots());
print_r($attributes);
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

protected _initialize ()

Initialize the metadata for certain table

public array readMetaData (Phalcon\Mvc\ModelInterface $model)

Reads meta-data for certain model

public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index)

Reads meta-data for certain model using a MODEL_* constant

public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index, mixed $data)

Writes meta-data for certain model using a MODEL_* constant

public array readColumnMap (Phalcon\Mvc\ModelInterface $model)

Reads the ordered/reversed column map for certain model

public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, int $index)

Reads column-map information for certain model using a MODEL_* constant

public array getAttributes (Phalcon\Mvc\ModelInterface $model)

Returns table attributes names (fields)

public array getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model)

Returns an array of fields which are part of the primary key

public array getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model)

Returns an arrau of fields which are not part of the primary key

public array getNotNullAttributes (Phalcon\Mvc\ModelInterface $model)

Returns an array of not null attributes

public array getDataTypes (Phalcon\Mvc\ModelInterface $model)

Returns attributes and their data types

public array getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model)

Returns attributes which types are numerical

public string getIdentityField (Phalcon\Mvc\ModelInterface $model)

Returns the name of identity field (if one is present)

public array getBindTypes (Phalcon\Mvc\ModelInterface $model)

Returns attributes and their bind data types

public array getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model)

Returns attributes that must be ignored from the INSERT SQL generation

public array getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model)

Returns attributes that must be ignored from the UPDATE SQL generation

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

Set the attributes that must be ignored from the INSERT SQL generation

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

Set the attributes that must be ignored from the UPDATE SQL generation

public array getColumnMap (Phalcon\Mvc\ModelInterface $model)

Returns the column map if any

public array getReverseColumnMap (Phalcon\Mvc\ModelInterface $model)

Returns the reverse column map if any

public boolean hasAttribute (Phalcon\Mvc\ModelInterface $model, unknown $attribute)

Check if a model has certain attribute

public boolean isEmpty ()

Checks if the internal meta-data container is empty

public reset ()

Resets internal meta-data in order to regenerate it

Class Phalcon\Mvc\Model\MetaData\Apc

extends Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface

Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch(‘$PMM$’) or apc_fetch(‘$PMM$my-app-id’)

<?php

 $metaData = new Phalcon\Mvc\Model\Metadata\Apc(array(
    'suffix' => 'my-app-id',
    'lifetime' => 86400
 ));
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct (array $options)

Phalcon\Mvc\Model\MetaData\Apc constructor

public array read (string $key)

Reads meta-data from APC

public write (string $key, array $data)

Writes the meta-data to APC

protected _initialize () inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public array readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model using a MODEL_* constant

public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

public array readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, int $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

public array getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

public array getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

public array getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an arrau of fields which are not part of the primary key

public array getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

public array getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

public array getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

public array getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

public array getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

public array getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

public array getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

public array getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

public boolean hasAttribute (Phalcon\Mvc\ModelInterface $model, unknown $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

public boolean isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

public reset () inherited from Phalcon\Mvc\Model\MetaData

Resets internal meta-data in order to regenerate it

Class Phalcon\Mvc\Model\MetaData\Files

extends Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface

Stores model meta-data in PHP files.

<?php

 $metaData = new Phalcon\Mvc\Model\Metadata\Files(array(
    'metaDataDir' => 'app/cache/metadata/'
 ));
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct (array $options)

Phalcon\Mvc\Model\MetaData\Files constructor

public array read (unknown $key)

Reads meta-data from files

public write (string $key, array $data)

Writes the meta-data to files

protected _initialize () inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public array readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model using a MODEL_* constant

public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

public array readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, int $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

public array getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

public array getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

public array getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an arrau of fields which are not part of the primary key

public array getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

public array getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

public array getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

public array getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

public array getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

public array getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

public array getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

public array getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

public boolean hasAttribute (Phalcon\Mvc\ModelInterface $model, unknown $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

public boolean isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

public reset () inherited from Phalcon\Mvc\Model\MetaData

Resets internal meta-data in order to regenerate it

Class Phalcon\Mvc\Model\MetaData\Memory

extends Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface

Stores model meta-data in memory. Data will be erased when the request finishes

Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct (array $options)

Phalcon\Mvc\Model\MetaData\Memory constructor

public array read (unknown $key)

Reads the meta-data from temporal memory

public write (string $key, array $metaData)

Writes the meta-data to temporal memory

protected _initialize () inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public array readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model using a MODEL_* constant

public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

public array readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, int $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

public array getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

public array getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

public array getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an arrau of fields which are not part of the primary key

public array getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

public array getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

public array getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

public array getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

public array getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

public array getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

public array getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

public array getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

public boolean hasAttribute (Phalcon\Mvc\ModelInterface $model, unknown $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

public boolean isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

public reset () inherited from Phalcon\Mvc\Model\MetaData

Resets internal meta-data in order to regenerate it

Class Phalcon\Mvc\Model\MetaData\Session

extends Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface

Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION[‘$PMM$’]

<?php

 $metaData = new Phalcon\Mvc\Model\Metadata\Session(array(
    'suffix' => 'my-app-id'
 ));
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct (array $options)

Phalcon\Mvc\Model\MetaData\Session constructor

public array read (unknown $key)

Reads meta-data from $_SESSION

public write (string $key, array $data)

Writes the meta-data to $_SESSION

protected _initialize () inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public array readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model using a MODEL_* constant

public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

public array readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, int $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

public array getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

public array getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

public array getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an arrau of fields which are not part of the primary key

public array getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

public array getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

public array getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

public array getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

public array getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

public array getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

public array getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

public array getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

public boolean hasAttribute (Phalcon\Mvc\ModelInterface $model, unknown $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

public boolean isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

public reset () inherited from Phalcon\Mvc\Model\MetaData

Resets internal meta-data in order to regenerate it

Class Phalcon\Mvc\Model\Query

implements Phalcon\Mvc\Model\QueryInterface, Phalcon\DI\InjectionAwareInterface

This class takes a PHQL intermediate representation and executes it.

<?php

 $phql  = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b WHERE b.name = :name: ORDER BY c.name";

 $result = $manager->executeQuery($phql, array(
   'name' => 'Lamborghini'
 ));

 foreach ($result as $row) {
   echo "Name: ", $row->cars->name, "\n";
   echo "Price: ", $row->cars->price, "\n";
   echo "Taxes: ", $row->taxes, "\n";
 }
Constants

integer TYPE_SELECT

integer TYPE_INSERT

integer TYPE_UPDATE

integer TYPE_DELETE

Methods

public __construct (string $phql)

Phalcon\Mvc\Model\Query constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public Phalcon\DiInterface getDI ()

Returns the dependency injection container

protected string _getQualified ()

Replaces the model’s name to its source name in a qualifed-name expression

protected string _getCallArgument ()

Resolves a expression in a single call argument

protected string _getFunctionCall ()

Resolves a expression in a single call argument

protected string _getExpression ()

Resolves an expression from its intermediate code into a string

protected array _getSelectColumn ()

Resolves a column from its intermediate representation into an array used to determine if the resulset produced is simple or complex

protected string _getTable ()

Resolves a table in a SELECT statement checking if the model exists

protected array _getJoin ()

Resolves a JOIN clause checking if the associated models exist

protected string _getJoinType ()

Resolves a JOIN type

protected array _getJoins ()

Resolves all the JOINS in a SELECT statement

protected string _getOrderClause ()

Returns a processed order clause for a SELECT statement

protected string _getGroupClause ()

Returns a processed group clause for a SELECT statement

protected array _prepareSelect ()

Analyzes a SELECT intermediate code and produces an array to be executed later

protected array _prepareInsert ()

Analyzes an INSERT intermediate code and produces an array to be executed later

protected array _prepareUpdate ()

Analyzes an UPDATE intermediate code and produces an array to be executed later

protected array _prepareDelete ()

Analyzes a DELETE intermediate code and produces an array to be executed later

public array parse ()

Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another intermediate representation that could be executed by Phalcon\Mvc\Model\Query

public cache (array $cacheOptions)

Sets the cache parameters of the query

public getCacheOptions ()

Returns the current cache options

public Phalcon\Cache\BackendInterface getCache ()

Returns the current cache backend instance

protected Phalcon\Mvc\Model\ResultsetInterface _executeSelect ()

Executes the SELECT intermediate representation producing a Phalcon\Mvc\Model\Resultset

protected Phalcon\Mvc\Model\Query\StatusInterface _executeInsert ()

Executes the INSERT intermediate representation producing a Phalcon\Mvc\Model\Query\Status

protected Phalcon\Mvc\Model\ResultsetInterface _getRelatedRecords ()

Query the records on which the UPDATE/DELETE operation well be done

protected Phalcon\Mvc\Model\Query\StatusInterface _executeUpdate ()

Executes the UPDATE intermediate representation producing a Phalcon\Mvc\Model\Query\Status

protected Phalcon\Mvc\Model\Query\StatusInterface _executeDelete ()

Executes the DELETE intermediate representation producing a Phalcon\Mvc\Model\Query\Status

public mixed execute (array $bindParams, array $bindTypes)

Executes a parsed PHQL statement

public setType (int $type)

Sets the type of PHQL statement to be executed

public int getType ()

Gets the type of PHQL statement executed

public setIntermediate (array $intermediate)

Allows to set the IR to be executed

public array getIntermediate ()

Returns the intermediate representation of the PHQL statement

Class Phalcon\Mvc\Model\Query\Builder

implements Phalcon\DI\InjectionAwareInterface

Helps to create PHQL queries using an OO interface

<?php
Methods

public __construct (array $params)

public Phalcon\Mvc\Model\Query\Builder setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public Phalcon\DiInterface getDI ()

Returns the DependencyInjector container

public Phalcon\Mvc\Model\Query\Builder columns (string|array $columns)

Sets the columns to be queried

public string|array getColumns ()

Return the columns to be queried

public Phalcon\Mvc\Model\Query\Builder from (string|array $models)

Sets the models who makes part of the query

public Phalcon\Mvc\Model\Query\Builder addFrom (string $model, string $alias)

Add a model to take part of the query

public string|array getFrom ()

Return the models who makes part of the query

public Phalcon\Mvc\Model\Query\Builder join (string $model, string $conditions, string $alias)

Sets the models who makes part of the query

public Phalcon\Mvc\Model\Query\Builder where (string $conditions)

Sets conditions for the query

public string|array getWhere ()

Return the conditions for the query

public Phalcon\Mvc\Model\Query\Builder orderBy (string $orderBy)

Sets a ORDER BY condition clause

public string|array getOrderBy ()

Return the set ORDER BY clause

public Phalcon\Mvc\Model\Query\Builder having (string $having)

Sets a HAVING condition clause

public string|array getHaving ()

Return the columns to be queried

public Phalcon\Mvc\Model\Query\Builder limit (int $limit, int $offset)

Sets a LIMIT clause

public string|array getLimit ()

Returns the current LIMIT clause

public Phalcon\Mvc\Model\Query\Builder groupBy (string $group)

Sets a LIMIT clause

public string getGroupBy ()

Returns the GROUP BY clause

public string getPhql ()

Returns a PHQL statement built based on the builder parameters

public Phalcon\Mvc\Model\Query getQuery ()

Returns the query built

Class Phalcon\Mvc\Model\Query\Lang

PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. It allows Phalcon to offer a unified SQL language to the developer, while internally doing all the work of translating PHQL instructions to the most optimal SQL instructions depending on the RDBMS type associated with a model. To achieve the highest performance possible, we wrote a parser that uses the same technology as SQLite. This technology provides a small in-memory parser with a very low memory footprint that is also thread-safe.

<?php

 $intermediate = Phalcon\Mvc\Model\Query\Lang::parsePHQL("SELECT r.* FROM Robots r LIMIT 10");
Methods

public static string parsePHQL (string $phql)

Parses a PHQL statement returning an intermediate representation (IR)

Class Phalcon\Mvc\Model\Query\Status

implements Phalcon\Mvc\Model\Query\StatusInterface

This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails

<?php

$phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:";
$status = $app->modelsManager->executeQuery($phql, array(
   'id' => 100,
   'name' => 'Astroy Boy',
   'type' => 'mechanical',
   'year' => 1959
));

\//Check if the update was successful
if($status->success()==true){
   echo 'OK';
}
Methods

public __construct (boolean $success, Phalcon\Mvc\ModelInterface $model)

public Phalcon\Mvc\ModelInterface getModel ()

Returns the model which executed the action

public Phalcon\Mvc\Model\Message [] getMessages ()

Returns the messages produced by a operation failed

public boolean success ()

Allows to check if the executed operation was successful

Class Phalcon\Mvc\Model\Resultset

implements Phalcon\Mvc\Model\ResultsetInterface, Iterator, Traversable, SeekableIterator, Countable, ArrayAccess, Serializable

This component allows to Phalcon\Mvc\Model returns large resulsets with the minimum memory consumption Resulsets can be traversed using a standard foreach or a while statement. If a resultset is serialized it will dump all the rows into a big array. Then unserialize will retrieve the rows as they were before serializing.

<?php

 //Using a standard foreach
 $robots = $Robots::find(array("type='virtual'", "order" => "name"));
 foreach($robots as $robot){
  echo $robot->name, "\n";
 }

 //Using a while
 $robots = $Robots::find(array("type='virtual'", "order" => "name"));
 $robots->rewind();
 while($robots->valid()){
  $robot = $robots->current();
  echo $robot->name, "\n";
  $robots->next();
 }
Methods

public next ()

Moves cursor to next row in the resultset

public int key ()

Gets pointer number of active row in the resultset

public rewind ()

Rewinds resultset to its beginning

public seek (int $position)

Changes internal pointer to a specific position in the resultset

public int count ()

Counts how many rows are in the resultset

public boolean offsetExists (int $index)

Checks whether offset exists in the resultset

public Phalcon\Mvc\Model offsetGet (int $index)

Gets row in a specific position of the resultset

public offsetSet (int $index, Phalcon\Mvc\Model $value)

Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public offsetUnset (int $offset)

Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public Phalcon\Mvc\Model getFirst ()

Get first row in the resultset

public Phalcon\Mvc\Model getLast ()

Get last row in the resultset

public setIsFresh (boolean $isFresh)

Set if the resultset is fresh or an old one cached

public boolean isFresh ()

Tell if the resultset if fresh or an old one cached

public Phalcon\Cache\Backend getCache ()

Returns the associated cache for the resultset

public object current ()

Returns current row in the resultset

abstract public valid () inherited from Iterator

...

abstract public serialize () inherited from Serializable

...

abstract public unserialize (unknown $serialized) inherited from Serializable

...

Class Phalcon\Mvc\Model\Resultset\Complex

extends Phalcon\Mvc\Model\Resultset

implements Serializable, ArrayAccess, Countable, SeekableIterator, Traversable, Iterator, Phalcon\Mvc\Model\ResultsetInterface

Complex resultsets may include complete objects and scalar values. This class builds every complex row as the’re required

Methods

public __construct (array $columnsTypes, Phalcon\Db\ResultInterface $result, Phalcon\Cache\BackendInterface $cache)

Phalcon\Mvc\Model\Resultset\Complex constructor

public boolean valid ()

Check whether internal resource has rows to fetch

public string serialize ()

Serializing a resultset will dump all related rows into a big array

public unserialize (string $data)

Unserializing a resultset will allow to only works on the rows present in the saved state

public next () inherited from Phalcon\Mvc\Model\Resultset

Moves cursor to next row in the resultset

public int key () inherited from Phalcon\Mvc\Model\Resultset

Gets pointer number of active row in the resultset

public rewind () inherited from Phalcon\Mvc\Model\Resultset

Rewinds resultset to its beginning

public seek (int $position) inherited from Phalcon\Mvc\Model\Resultset

Changes internal pointer to a specific position in the resultset

public int count () inherited from Phalcon\Mvc\Model\Resultset

Counts how many rows are in the resultset

public boolean offsetExists (int $index) inherited from Phalcon\Mvc\Model\Resultset

Checks whether offset exists in the resultset

public Phalcon\Mvc\Model offsetGet (int $index) inherited from Phalcon\Mvc\Model\Resultset

Gets row in a specific position of the resultset

public offsetSet (int $index, Phalcon\Mvc\Model $value) inherited from Phalcon\Mvc\Model\Resultset

Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public offsetUnset (int $offset) inherited from Phalcon\Mvc\Model\Resultset

Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public Phalcon\Mvc\Model getFirst () inherited from Phalcon\Mvc\Model\Resultset

Get first row in the resultset

public Phalcon\Mvc\Model getLast () inherited from Phalcon\Mvc\Model\Resultset

Get last row in the resultset

public setIsFresh (boolean $isFresh) inherited from Phalcon\Mvc\Model\Resultset

Set if the resultset is fresh or an old one cached

public boolean isFresh () inherited from Phalcon\Mvc\Model\Resultset

Tell if the resultset if fresh or an old one cached

public Phalcon\Cache\Backend getCache () inherited from Phalcon\Mvc\Model\Resultset

Returns the associated cache for the resultset

public object current () inherited from Phalcon\Mvc\Model\Resultset

Returns current row in the resultset

Class Phalcon\Mvc\Model\Resultset\Simple

extends Phalcon\Mvc\Model\Resultset

implements Serializable, ArrayAccess, Countable, SeekableIterator, Traversable, Iterator, Phalcon\Mvc\Model\ResultsetInterface

Simple resultsets only contains a complete object. This class builds every complete object as it’s required

Methods

public __construct (unknown $columnMap, Phalcon\Mvc\Model $model, Phalcon\Db\Result\Pdo $result, Phalcon\Cache\Backend $cache)

Phalcon\Mvc\Model\Resultset\Simple constructor

public boolean valid ()

Check whether internal resource has rows to fetch

public string serialize ()

Serializing a resultset will dump all related rows into a big array

public unserialize (string $data)

Unserializing a resultset will allow to only works on the rows present in the saved state

public next () inherited from Phalcon\Mvc\Model\Resultset

Moves cursor to next row in the resultset

public int key () inherited from Phalcon\Mvc\Model\Resultset

Gets pointer number of active row in the resultset

public rewind () inherited from Phalcon\Mvc\Model\Resultset

Rewinds resultset to its beginning

public seek (int $position) inherited from Phalcon\Mvc\Model\Resultset

Changes internal pointer to a specific position in the resultset

public int count () inherited from Phalcon\Mvc\Model\Resultset

Counts how many rows are in the resultset

public boolean offsetExists (int $index) inherited from Phalcon\Mvc\Model\Resultset

Checks whether offset exists in the resultset

public Phalcon\Mvc\Model offsetGet (int $index) inherited from Phalcon\Mvc\Model\Resultset

Gets row in a specific position of the resultset

public offsetSet (int $index, Phalcon\Mvc\Model $value) inherited from Phalcon\Mvc\Model\Resultset

Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public offsetUnset (int $offset) inherited from Phalcon\Mvc\Model\Resultset

Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public Phalcon\Mvc\Model getFirst () inherited from Phalcon\Mvc\Model\Resultset

Get first row in the resultset

public Phalcon\Mvc\Model getLast () inherited from Phalcon\Mvc\Model\Resultset

Get last row in the resultset

public setIsFresh (boolean $isFresh) inherited from Phalcon\Mvc\Model\Resultset

Set if the resultset is fresh or an old one cached

public boolean isFresh () inherited from Phalcon\Mvc\Model\Resultset

Tell if the resultset if fresh or an old one cached

public Phalcon\Cache\Backend getCache () inherited from Phalcon\Mvc\Model\Resultset

Returns the associated cache for the resultset

public object current () inherited from Phalcon\Mvc\Model\Resultset

Returns current row in the resultset

Class Phalcon\Mvc\Model\Row

implements ArrayAccess, Phalcon\Mvc\Model\ResultInterface

This component allows Phalcon\Mvc\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x].

Methods

public setForceExists (boolean $forceExists)

Forces that a model doesn’t need to be checked if exists before store it

public boolean offsetExists (int $index)

Checks whether offset exists in the row

public string|PhalconMvcModelInterface offsetGet (int $index)

Gets row in a specific position of the row

public offsetSet (int $index, Phalcon\Mvc\ModelInterface $value)

Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public offsetUnset (int $offset)

Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

Class Phalcon\Mvc\Model\Transaction

implements Phalcon\Mvc\Model\TransactionInterface

Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. Phalcon\Transaction is intended to be used with Phalcon_Model_Base. Phalcon Transactions should be created using Phalcon\Transaction\Manager.

<?php

try {

  $transaction = Phalcon\Mvc\Model\Transaction\Manager::get();

  $robot = new Robots();
  $robot->setTransaction($transaction);
  $robot->name = 'WALL·E';
  $robot->created_at = date('Y-m-d');
  if($robot->save()==false){
    $transaction->rollback("Can't save robot");
  }

  $robotPart = new RobotParts();
  $robotPart->setTransaction($transaction);
  $robotPart->type = 'head';
  if($robotPart->save()==false){
    $transaction->rollback("Can't save robot part");
  }

  $transaction->commit();

}
catch(Phalcon\Mvc\Model\Transaction\Failed $e){
  echo 'Failed, reason: ', $e->getMessage();
}
Methods

public __construct (Phalcon\DiInterface $dependencyInjector, boolean $autoBegin)

Phalcon\Mvc\Model\Transaction constructor

public setTransactionManager (Phalcon\Mvc\Model\Transaction\ManagerInterface $manager)

Sets transaction manager related to the transaction

public boolean begin ()

Starts the transaction

public boolean commit ()

Commits the transaction

public boolean rollback (string $rollbackMessage, Phalcon\Mvc\ModelInterface $rollbackRecord)

Rollbacks the transaction

public string getConnection ()

Returns connection related to transaction

public setIsNewTransaction (boolean $isNew)

Sets if is a reused transaction or new once

public setRollbackOnAbort (boolean $rollbackOnAbort)

Sets flag to rollback on abort the HTTP connection

public boolean isManaged ()

Checks whether transaction is managed by a transaction manager

public array getMessages ()

Returns validations messages from last save try

public boolean isValid ()

Checks whether internal connection is under an active transaction

public setRollbackedRecord (Phalcon\Mvc\ModelInterface $record)

Sets object which generates rollback action

Class Phalcon\Mvc\Model\Transaction\Exception

extends Phalcon\Mvc\Model\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Model\Transaction\Failed

extends Exception

Phalcon\Mvc\Model\Transaction\Failed will be thrown to exit a try/catch block for transactions

Methods

public __construct (string $message, Phalcon\Mvc\ModelInterface $record)

Phalcon\Mvc\Model\Transaction\Failed constructor

public Phalcon\Mvc\Model\MessageInterface [] getRecordMessages ()

Returns validation record messages which stop the transaction

public Phalcon\Mvc\ModelInterface getRecord ()

Returns validation record messages which stop the transaction

final private Exception __clone () inherited from Exception

Clone the exception

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Model\Transaction\Manager

implements Phalcon\Mvc\Model\Transaction\ManagerInterface, Phalcon\DI\InjectionAwareInterface

A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. This class manages the objects that compose a transaction. A trasaction produces a unique connection that is passed to every object part of the transaction.

<?php

try {

  use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager;

  $transactionManager = new TransactionManager();

  $transaction = $transactionManager->get();

  $robot = new Robots();
  $robot->setTransaction($transaction);
  $robot->name = 'WALL·E';
  $robot->created_at = date('Y-m-d');
  if($robot->save()==false){
    $transaction->rollback("Can't save robot");
  }

  $robotPart = new RobotParts();
  $robotPart->setTransaction($transaction);
  $robotPart->type = 'head';
  if($robotPart->save()==false){
    $transaction->rollback("Can't save robot part");
  }

  $transaction->commit();

}
catch(Phalcon\Mvc\Model\Transaction\Failed $e){
  echo 'Failed, reason: ', $e->getMessage();
}
Methods

public __construct (Phalcon\DiInterface $dependencyInjector)

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public Phalcon\DiInterface getDI ()

Returns the dependency injection container

public boolean has ()

Checks whether manager has an active transaction

public Phalcon\Mvc\Model\TransactionInterface get (boolean $autoBegin)

Returns a new Phalcon\Mvc\Model\Transaction or an already created once

public rollbackPendent ()

Rollbacks active transactions within the manager

public commit ()

Commmits active transactions within the manager

public rollback (boolean $collect)

Rollbacks active transactions within the manager Collect will remove transaction from the manager

public notifyRollback (Phalcon\Mvc\Model\TransactionInterface $transaction)

Notifies the manager about a rollbacked transaction

public notifyCommit (Phalcon\Mvc\Model\TransactionInterface $transaction)

Notifies the manager about a commited transaction

protected _collectTransaction ()

Removes transactions from the TransactionManager

public collectTransactions ()

Remove all the transactions from the manager

Class Phalcon\Mvc\Model\Validator

This is a base class for Phalcon\Mvc\Model validators

Methods

public __construct (array $options)

Phalcon\Mvc\Model\Validator constructor

protected appendMessage ()

Appends a message to the validator

public array getMessages ()

Returns messages generated by the validator

protected array getOptions ()

Returns all the options from the validator

protected mixed getOption ()

Returns an option

protected boolean isSetOption ()

Check whether a option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Email

extends Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Allows to validate if email fields has correct values

<?php

use Phalcon\Mvc\Model\Validator\Email as EmailValidator;

class Subscriptors extends Phalcon\Mvc\Model
{

    public function validation()
    {
            $this->validate(new EmailValidator(array(
                    'field' => 'electronic_mail'
            )));
            if ($this->validationHasFailed() == true) {
                    return false;
            }
    }

}
Methods

public boolean validate (Phalcon\Mvc\ModelInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage () inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public array getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

protected array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

protected mixed getOption () inherited from Phalcon\Mvc\Model\Validator

Returns an option

protected boolean isSetOption () inherited from Phalcon\Mvc\Model\Validator

Check whether a option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Exclusionin

extends Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Phalcon\Mvc\Model\Validator\ExclusionIn Check if a value is not included into a list of values

<?php

use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionInValidator;

class Subscriptors extends Phalcon\Mvc\Model
{

    public function validation()
    {
            $this->validate(new ExclusionInValidator(array(
                    'field' => 'status',
                    'domain' => array('A', 'I')
            )));
            if ($this->validationHasFailed() == true) {
                    return false;
            }
    }

}
Methods

public boolean validate (Phalcon\Mvc\ModelInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage () inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public array getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

protected array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

protected mixed getOption () inherited from Phalcon\Mvc\Model\Validator

Returns an option

protected boolean isSetOption () inherited from Phalcon\Mvc\Model\Validator

Check whether a option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Inclusionin

extends Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Phalcon\Mvc\Model\Validator\InclusionIn Check if a value is included into a list of values

<?php

use Phalcon\Mvc\Model\Validator\InclusionIn as InclusionInValidator;

class Subscriptors extends Phalcon\Mvc\Model
{

    public function validation()
    {
            $this->validate(new InclusionInValidator(array(
                    'field' => 'status',
                    'domain' => array('A', 'I')
            )));
            if ($this->validationHasFailed() == true) {
                    return false;
            }
    }

}
Methods

public boolean validate (Phalcon\Mvc\ModelInterface $record)

Executes validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage () inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public array getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

protected array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

protected mixed getOption () inherited from Phalcon\Mvc\Model\Validator

Returns an option

protected boolean isSetOption () inherited from Phalcon\Mvc\Model\Validator

Check whether a option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Numericality

extends Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Allows to validate if a field has a valid numeric format

<?php

use Phalcon\Mvc\Model\Validator\Numericality as NumericalityValidator;

class Products extends Phalcon\Mvc\Model
{

  public function validation()
  {
      $this->validate(new NumericalityValidator(array(
          'field' => 'price'
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
  }

}
Methods

public boolean validate (Phalcon\Mvc\ModelInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage () inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public array getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

protected array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

protected mixed getOption () inherited from Phalcon\Mvc\Model\Validator

Returns an option

protected boolean isSetOption () inherited from Phalcon\Mvc\Model\Validator

Check whether a option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\PresenceOf

extends Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Allows to validate if a filed have a value different of null and empty string (“”)

<?php

use Phalcon\Mvc\Model\Validator\PresenceOf;

class Subscriptors extends Phalcon\Mvc\Model
{

  public function validation()
  {
      $this->validate(new PresenceOf(array(
          'field' => 'name',
          'message' => 'The name is required'
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
  }

}
Methods

public boolean validate (Phalcon\Mvc\ModelInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage () inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public array getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

protected array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

protected mixed getOption () inherited from Phalcon\Mvc\Model\Validator

Returns an option

protected boolean isSetOption () inherited from Phalcon\Mvc\Model\Validator

Check whether a option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Regex

extends Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Allows to validate if the value of a field matches a regular expression

<?php

use Phalcon\Mvc\Model\Validator\Regex as RegexValidator;

class Subscriptors extends Phalcon\Mvc\Model
{

  public function validation()
  {
      $this->validate(new RegexValidator(array(
          'field' => 'created_at',
          'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/'
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
  }

}
Methods

public boolean validate (Phalcon\Mvc\ModelInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage () inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public array getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

protected array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

protected mixed getOption () inherited from Phalcon\Mvc\Model\Validator

Returns an option

protected boolean isSetOption () inherited from Phalcon\Mvc\Model\Validator

Check whether a option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\StringLength

extends Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Simply validates specified string length constraints

<?php

use Phalcon\Mvc\Model\Validator\StringLength as StringLengthValidator;

class Subscriptors extends Phalcon\Mvc\Model
{

public function validation()
{
    $this->validate(new StringLengthValidator(array(
            'field' => 'name_last',
            'max' => 50,
            'min' => 2,
          'maximumMessage' => 'We don't like really long names',
          'minimumMessage' => 'We want more than just their initials'
    )));
    if ($this->validationHasFailed() == true) {
            return false;
    }
}

}
Methods

public boolean validate (Phalcon\Mvc\ModelInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage () inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public array getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

protected array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

protected mixed getOption () inherited from Phalcon\Mvc\Model\Validator

Returns an option

protected boolean isSetOption () inherited from Phalcon\Mvc\Model\Validator

Check whether a option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Uniqueness

extends Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Validates that a field or a combination of a set of fields are not present more than once in the existing records of the related table

<?php

use Phalcon\Mvc\Model\Validator\Uniqueness as UniquenessValidator;

class Subscriptors extends Phalcon\Mvc\Model
{

  public function validation()
  {
      $this->validate(new UniquenessValidator(array(
          'field' => 'email'
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
  }

}
Methods

public boolean validate (Phalcon\Mvc\ModelInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage () inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public array getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

protected array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

protected mixed getOption () inherited from Phalcon\Mvc\Model\Validator

Returns an option

protected boolean isSetOption () inherited from Phalcon\Mvc\Model\Validator

Check whether a option has been defined in the validator options

Class Phalcon\Mvc\Router

implements Phalcon\Mvc\RouterInterface, Phalcon\DI\InjectionAwareInterface

Phalcon\Mvc\Router is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request

<?php

$router = new Phalcon\Mvc\Router();
$router->handle();
echo $router->getControllerName();
Methods

public __construct (boolean $defaultRoutes)

Phalcon\Mvc\Router constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

protected string _getRewriteUri ()

Get rewrite info

public setDefaultNamespace (string $namespaceName)

Sets the name of the default namespace

public setDefaultModule (string $moduleName)

Sets the name of the default module

public setDefaultController (string $controllerName)

Sets the default controller name

public setDefaultAction (string $actionName)

Sets the default action name

public setDefaults (array $defaults)

Sets an array of default paths

public handle (string $uri)

Handles routing information received from the rewrite engine

public Phalcon\Mvc\Router\Route add (string $pattern, string/array $paths, string $httpMethods)

Adds a route to the router on any HTTP method

public Phalcon\Mvc\Router\Route addGet (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is GET

public Phalcon\Mvc\Router\Route addPost (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is POST

public Phalcon\Mvc\Router\Route addPut (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is PUT

public Phalcon\Mvc\Router\Route addDelete (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is DELETE

public Phalcon\Mvc\Router\Route addOptions (string $pattern, string/array $paths)

Add a route to the router that only match if the HTTP method is OPTIONS

public Phalcon\Mvc\Router\Route addHead (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is HEAD

public clear ()

Removes all the pre-defined routes

public string getNamespaceName ()

Returns processed namespace name

public string getModuleName ()

Returns processed module name

public string getControllerName ()

Returns processed controller name

public string getActionName ()

Returns processed action name

public array getParams ()

Returns processed extra params

public Phalcon\Mvc\Router\Route getMatchedRoute ()

Returns the route that matchs the handled URI

public array getMatches ()

Return the sub expressions in the regular expression matched

public bool wasMatched ()

Check if the router macthes any of the defined routes

public Phalcon\Mvc\Router\Route [] getRoutes ()

Return all the routes defined in the router

public Phalcon\Mvc\Router\Route getRouteById (unknown $id)

Returns a route object by its id

public Phalcon\Mvc\Router\Route getRouteByName (unknown $name)

Returns a route object by its name

Class Phalcon\Mvc\Router\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Router\Route

implements Phalcon\Mvc\Router\RouteInterface

This class represents every route defined in the router.

Methods

public __construct (string $pattern, array $paths, array|string $httpMethods)

Phalcon\Mvc\Router\Route constructor

public string compilePattern (string $pattern)

Replaces placeholders from pattern returning a valid PCRE regular expression

public via (string|array $httpMethods)

Set one or more HTTP methods that constraint the matching of the route

public reConfigure (string $pattern, array $paths)

Reconfigure the route adding a new pattern and a set of paths

public string getName ()

Returns the route’s name

public setName (string $name)

Sets the route’s name

public setHttpMethods (string|array $httpMethods)

Sets a set of HTTP methods that constraint the matching of the route

public string getRouteId ()

Returns the route’s id

public string getPattern ()

Returns the route’s pattern

public string getCompiledPattern ()

Returns the route’s compiled pattern

public array getPaths ()

Returns the paths

public array getReversedPaths ()

Returns the paths using positions as keys and names as values

public string|array getHttpMethods ()

Returns the HTTP methods that constraint matching the route

public static reset ()

Resets the internal route id generator

Class Phalcon\Mvc\Url

implements Phalcon\Mvc\UrlInterface, Phalcon\DI\InjectionAwareInterface

This components aids in the generation of: URIs, URLs and Paths

<?php

 //Generate a url appending a uri to the base Uri
 echo $url->get('products/edit/1');

 //Generate a url for a predefined route
 echo $url->get(array('for' => 'blog-post', 'title' => 'some-cool-stuff', 'year' => '2012'));
Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public Phalcon\DiInterface getDI ()

Returns the DependencyInjector container

public setBaseUri (string $baseUri)

Sets a prefix to all the urls generated

<?php

$url->setBasePath('/invo/');

public string getBaseUri ()

Returns the prefix for all the generated urls. By default /

public setBasePath (string $basePath)

Sets a base paths for all the generated paths

<?php

$url->setBasePath('/var/www/');

public string getBasePath ()

Returns a base path

public string get (string|array $uri)

Generates a URL

public string path (string $path)

Generates a local path

Class Phalcon\Mvc\Url\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\User\Component

extends Phalcon\DI\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface

Methods

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI\Injectable

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\User\Module

extends Phalcon\DI\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface

Methods

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI\Injectable

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\User\Plugin

extends Phalcon\DI\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface

Methods

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI\Injectable

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\View

extends Phalcon\DI\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface, Phalcon\Mvc\ViewInterface

Phalcon\Mvc\View is a class for working with the “view” portion of the model-view-controller pattern. That is, it exists to help keep the view script separate from the model and controller scripts. It provides a system of helpers, output filters, and variable escaping.

<?php

 //Setting views directory
 $view = new Phalcon\Mvc\View();
 $view->setViewsDir('app/views/');

 $view->start();
 //Shows recent posts view (app/views/posts/recent.phtml)
 $view->render('posts', 'recent');
 $view->finish();

 //Printing views output
 echo $view->getContent();
Constants

integer LEVEL_MAIN_LAYOUT

integer LEVEL_AFTER_TEMPLATE

integer LEVEL_LAYOUT

integer LEVEL_BEFORE_TEMPLATE

integer LEVEL_ACTION_VIEW

integer LEVEL_NO_RENDER

Methods

public __construct (array $options)

Phalcon\Mvc\View constructor

public setViewsDir (string $viewsDir)

Sets views directory. Depending of your platform, always add a trailing slash or backslash

public string getViewsDir ()

Gets views directory

public setBasePath (string $basePath)

Sets base path. Depending of your platform, always add a trailing slash or backslash

<?php

 $view->setBasePath(__DIR__.'/');

public setRenderLevel (string $level)

Sets the render level for the view

<?php

 //Render the view related to the controller only
 $this->view->setRenderLevel(Phalcon\Mvc\View::LEVEL_VIEW);

public setMainView (unknown $viewPath)

Sets default view name. Must be a file without extension in the views directory

<?php

 //Renders as main view views-dir/inicio.phtml
 $this->view->setMainView('inicio');

public setTemplateBefore (string|array $templateBefore)

Appends template before controller layout

public cleanTemplateBefore ()

Resets any template before layouts

public setTemplateAfter (string|array $templateAfter)

Appends template after controller layout

public cleanTemplateAfter ()

Resets any template before layouts

public setParamToView (string $key, mixed $value)

Adds parameters to views (alias of setVar)

public setVar (string $key, mixed $value)

Adds parameters to views

public array getParamsToView ()

Returns parameters to views

public string getControllerName ()

Gets the name of the controller rendered

public string getActionName ()

Gets the name of the action rendered

public array getParams ()

Gets extra parameters of the action rendered

public start ()

Starts rendering process enabling the output buffering

protected array _loadTemplateEngines ()

Loads registered template engines, if none is registered it will use Phalcon\Mvc\View\Engine\Php

protected _engineRender ()

Checks whether view exists on registered extensions and render it

public registerEngines (array $engines)

Register templating engines

<?php

$this->view->registerEngines(array(
  ".phtml" => "Phalcon\Mvc\View\Engine\Php",
  ".volt" => "Phalcon\Mvc\View\Engine\Volt",
  ".mhtml" => "MyCustomEngine"
));

public render (string $controllerName, string $actionName, array $params)

Executes render process from dispatching data

<?php

 $view->start();
 //Shows recent posts view (app/views/posts/recent.phtml)
 $view->render('posts', 'recent');
 $view->finish();

public pick (string $renderView)

Choose a view different to render than last-controller/last-action

<?php

 class ProductsController extends Phalcon\Mvc\Controller
 {

    public function saveAction()
    {

         //Do some save stuff...

         //Then show the list view
         $this->view->pick("products/list");
    }
 }

public string partial (string $partialPath)

Renders a partial view

<?php

 //Show a partial inside another view
 $this->partial('shared/footer');

public finish ()

Finishes the render process by stopping the output buffering

protected Phalcon\Cache\BackendInterface _createCache ()

Create a Phalcon\Cache based on the internal cache options

public Phalcon\Cache\BackendInterface getCache ()

Returns the cache instance used to cache

public cache (boolean|array $options)

Cache the actual view render to certain level

public setContent (string $content)

Externally sets the view content

<?php

$this->view->setContent("<h1>hello</h1>");

public string getContent ()

Returns cached ouput from another view stage

public string getActiveRenderPath ()

Returns the path of the view that is currently rendered

public disable ()

Disables the auto-rendering process

public enable ()

Enables the auto-rendering process

public reset ()

Resets the view component to its factory default values

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI\Injectable

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\View\Engine

extends Phalcon\DI\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface

All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\Mvc\View component.

Methods

public __construct (Phalcon\Mvc\ViewInterface $view, Phalcon\DiInterface $dependencyInjector)

Phalcon\Mvc\View\Engine constructor

public array getContent ()

Returns cached ouput on another view stage

public string partial (string $partialPath)

Renders a partial inside another view

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI\Injectable

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\View\Engine\Php

extends Phalcon\Mvc\View\Engine

implements Phalcon\DI\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface, Phalcon\Mvc\View\EngineInterface

Adapter to use PHP itself as templating engine

Methods

public render (string $path, array $params, boolean $mustClean)

Renders a view using the template engine

public __construct (Phalcon\Mvc\ViewInterface $view, Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\View\Engine

Phalcon\Mvc\View\Engine constructor

public array getContent () inherited from Phalcon\Mvc\View\Engine

Returns cached ouput on another view stage

public string partial (string $partialPath) inherited from Phalcon\Mvc\View\Engine

Renders a partial inside another view

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\DI\Injectable

Sets the dependency injector

public Phalcon\DiInterface getDI () inherited from Phalcon\DI\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\View\Engine\Volt

extends Phalcon\Mvc\View\Engine

implements Phalcon\DI\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface, Phalcon\Mvc\View\EngineInterface

Designer friendly and fast template engine for PHP written in C

Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public Phalcon\DiInterface getDI ()

Returns the dependency injection container

public setOptions (array $options)

Set Volt’s options

public array getOptions ()

Return Volt’s options

public render (string $templatePath, array $params, boolean $mustClean)

Renders a view using the template engine

public int length (mixed $item)

Length filter

public __construct (Phalcon\Mvc\ViewInterface $view, Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\View\Engine

Phalcon\Mvc\View\Engine constructor

public array getContent () inherited from Phalcon\Mvc\View\Engine

Returns cached ouput on another view stage

public string partial (string $partialPath) inherited from Phalcon\Mvc\View\Engine

Renders a partial inside another view

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\DI\Injectable

Sets the event manager

public Phalcon\Events\ManagerInterface getEventsManager () inherited from Phalcon\DI\Injectable

Returns the internal event manager

public __get (string $propertyName) inherited from Phalcon\DI\Injectable

Magic method __get

Class Phalcon\Mvc\View\Engine\Volt\Compiler

This class reads and compiles volt templates into PHP plain code

Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

protected string _functionCall ()

Resolves function intermediate code into PHP function calls

protected string _filter ()

Resolves filter intermediate code into PHP function calls

public string _expression (array $expr, bool $extendsMode, bool $prependDollar)

Resolves an expression node in an AST volt tree

protected string _statementList ()

Traverses a statement list compiling each of its nodes

protected string _compileSource ()

Compiles a Volt source code returning a PHP plain version

public string compileString (string $viewCode, boolean $extendsMode)

Compiles a template in a string

public compile (string $path, string $compiledPath)

Compiles a template into a file

public array parse (string $viewCode)

Parses a Volt template returning its intermediate representation

Class Phalcon\Mvc\View\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Paginator\Adapter\Model

implements Phalcon\Paginator\AdapterInterface

This adapter allows to paginate data using Phalcon\Model resultsets.

Methods

public __construct (array $config)

Phalcon\Paginator\Adapter\Model constructor

public setCurrentPage (int $page)

Set the current page number

public stdClass getPaginate ()

Returns a slice of the resultset to show in the pagination

Class Phalcon\Paginator\Adapter\NativeArray

implements Phalcon\Paginator\AdapterInterface

Component of pagination by array data

Methods

public __construct (array $config)

Phalcon\Paginator\Adapter\NativeArray constructor

public setCurrentPage (int $page)

Set the current page number

public stdClass getPaginate ()

Returns a slice of the resultset to show in the pagination

Class Phalcon\Paginator\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Session

Class Phalcon\Session\Adapter

Base class for Phalcon\Session adapters

Methods

public __construct (array $options)

Phalcon\Session\Adapter construtor

public start ()

Starts session, optionally using an adapter

public setOptions (array $options)

Sets session options

public array getOptions ()

Get internal options

public get (string $index)

Gets a session variable from an application context

public set (string $index, string $value)

Sets a session variable in an application context

public has (string $index)

Check whether a session variable is set in an application context

public remove (string $index)

Removes a session variable from an application context

public string getId ()

Returns active session id

public boolean isStarted ()

Check whether the session has been started

public boolean destroy ()

Destroys the active session

Class Phalcon\Session\Adapter\Files

extends Phalcon\Session\Adapter

implements Phalcon\Session\AdapterInterface

Methods

public __construct (array $options) inherited from Phalcon\Session\Adapter

Phalcon\Session\Adapter construtor

public start () inherited from Phalcon\Session\Adapter

Starts session, optionally using an adapter

public setOptions (array $options) inherited from Phalcon\Session\Adapter

Sets session options

public array getOptions () inherited from Phalcon\Session\Adapter

Get internal options

public get (string $index) inherited from Phalcon\Session\Adapter

Gets a session variable from an application context

public set (string $index, string $value) inherited from Phalcon\Session\Adapter

Sets a session variable in an application context

public has (string $index) inherited from Phalcon\Session\Adapter

Check whether a session variable is set in an application context

public remove (string $index) inherited from Phalcon\Session\Adapter

Removes a session variable from an application context

public string getId () inherited from Phalcon\Session\Adapter

Returns active session id

public boolean isStarted () inherited from Phalcon\Session\Adapter

Check whether the session has been started

public boolean destroy () inherited from Phalcon\Session\Adapter

Destroys the active session

Class Phalcon\Session\Bag

implements Phalcon\DI\InjectionAwareInterface, Phalcon\Session\BagInterface

This component helps to separate session data into “namespaces”. Working by this way you can easily create groups of session variables into the application

<?php

 $user = new Phalcon\Session\Bag();
 $user->name = "Kimbra Johnson";
 $user->age = 22;
Methods

public __construct (unknown $name)

Phalcon\Session\Bag constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public Phalcon\DiInterface getDI ()

Returns the DependencyInjector container

public initialize ()

Initializes the session bag. This method must not be called directly, the class calls it when its internal data is accesed

public destroy ()

Destroyes the session bag

public __set (string $property, string $value)

Setter of values

public string __get (string $property)

Getter of values

public boolean __isset (string $property)

Isset property

Class Phalcon\Session\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Tag

Phalcon\Tag is designed to simplify building of HTML tags. It provides a set of helpers to generate HTML in a dynamic way. This component is an abstract class that you can extend to add more helpers.

Constants

integer HTML32

integer HTML401_STRICT

integer HTML401_TRANSITIONAL

integer HTML401_FRAMESET

integer HTML5

integer XHTML10_STRICT

integer XHTML10_TRANSITIONAL

integer XHTML10_FRAMESET

integer XHTML11

integer XHTML20

integer XHTML5

Methods

public static setDI (unknown $dependencyInjector)

Sets the dependency injector container.

public static Phalcon\DiInterface getDI ()

Internally gets the request dispatcher

public static Phalcon\Mvc\UrlInterface getUrlService ()

Return a URL service from the DI

public static Phalcon\Mvc\DispatcherInterface getDispatcherService ()

Returns a Dispatcher service from the DI

public static setDefault (string $id, string $value)

Assigns default values to generated tags by helpers

<?php

 //Assigning "peter" to "name" component
 Phalcon\Tag::setDefault("name", "peter");

 //Later in the view
 echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default

public static displayTo (string $id, string $value)

Alias of Phalcon\Tag::setDefault

public static mixed getValue (string $name)

Every helper calls this function to check whether a component has a predefined value using Phalcon\Tag::setDefault or value from $_POST

public static resetInput ()

Resets the request and internal values to avoid those fields will have any default value

public static string linkTo (array $parameters, unknown $text)

Builds a HTML A tag using framework conventions

<?php

echo Phalcon\Tag::linkTo('signup/register', 'Register Here!');

protected static string _inputField ()

Builds generic INPUT tags

public static string textField (array $parameters)

Builds a HTML input[type=”text”] tag

<?php

echo Phalcon\Tag::textField(array("name", "size" => 30))

public static string passwordField (array $parameters)

Builds a HTML input[type=”password”] tag

<?php

 echo Phalcon\Tag::passwordField(array("name", "size" => 30))

public static string hiddenField (array $parameters)

Builds a HTML input[type=”hidden”] tag

<?php

 echo Phalcon\Tag::hiddenField(array("name", "value" => "mike"))

public static string fileField (array $parameters)

Builds a HTML input[type=”file”] tag

<?php

 echo Phalcon\Tag::fileField("file")

public static string checkField (array $parameters)

Builds a HTML input[type=”check”] tag

<?php

 echo Phalcon\Tag::checkField(array("name", "size" => 30))

public static string radioField (array $parameters)

Builds a HTML input[type=”radio”] tag

<?php

 echo Phalcon\Tag::radioField(array("name", "size" => 30))

public static string submitButton (unknown $parameters)

Builds a HTML input[type=”submit”] tag

<?php

 echo Phalcon\Tag::submitButton("Save")

public static string selectStatic (array $parameters, unknown $data)

Builds a HTML SELECT tag using a PHP array for options

<?php

echo Phalcon\Tag::selectStatic("status", array("A" => "Active", "I" => "Inactive"))

public static string select (unknown $parameters, unknown $data)

Builds a HTML SELECT tag using a Phalcon_Model resultset as options

<?php

echo Phalcon\Tag::selectStatic(array(
    "robotId",
    Robots::find("type = 'mechanical'"),
    "using" => array("id", "name")
    ));

public static string textArea (array $parameters)

Builds a HTML TEXTAREA tag

<?php

 echo Phalcon\Tag::textArea(array("comments", "cols" => 10, "rows" => 4))

public static string form (array $parameters)

Builds a HTML FORM tag

<?php

 echo Phalcon\Tag::form("posts/save");
 echo Phalcon\Tag::form(array("posts/save", "method" => "post"));

Volt syntax:

<?php

 {{ form("posts/save") }}
 {{ form("posts/save", "method": "post") }}

public static string endForm ()

Builds a HTML close FORM tag

public static setTitle (string $title)

Set the title of view content

public static appendTitle (string $title)

Add to title of view content

public static prependTitle (string $title)

Add before the title of view content

public static string getTitle ()

Get the title of view content

public static string stylesheetLink (array $parameters, boolean $local)

Builds a LINK[rel=”stylesheet”] tag

<?php

 echo Phalcon\Tag::stylesheetLink("http://fonts.googleapis.com/css?family=Rosario", false);
 echo Phalcon\Tag::stylesheetLink("css/style.css");

public static string javascriptInclude (array $parameters, boolean $local)

Builds a SCRIPT[type=”javascript”] tag

<?php

 echo Phalcon\Tag::javascriptInclude("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false);
 echo Phalcon\Tag::javascriptInclude("javascript/jquery.js");

Volt syntax:

<?php

 {{ javascript_include("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false) }}
 {{ javascript_include("javascript/jquery.js") }}

public static string image (array $parameters)

Builds HTML IMG tags

public static text friendlyTitle (string $text, string $separator, boolean $lowercase)

Converts texts into URL-friendly titles

public static setDocType (string $doctype)

Set the document type of content

public static string getDocType ()

Get the document type declaration of content

Class Phalcon\Tag\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Tag\Select

Generates a SELECT html tag using a static array of values or a Phalcon\Mvc\Model resultset

Methods

public static selectField (array $parameters, array $data)

Generates a SELECT tag

protected static _optionsFromResultset ()

Generate the OPTION tags based on the rows

protected static _optionsFromArray ()

...

Class Phalcon\Text

Provides utilities when working with strings

Methods

public static string camelize (string $str)

Converts strings to camelize style

<?php

echo Phalcon\Text::camelize('coco_bongo'); //CocoBongo

public static string uncamelize (string $str)

Uncamelize strings which are camelized

<?php

echo Phalcon\Text::camelize('CocoBongo'); //coco_bongo

Class Phalcon\Translate

Class Phalcon\Translate\Adapter

implements ArrayAccess

Base class for Phalcon\Translate adapters

Methods

public string _ (string $translateKey, array $placeholders)

Returns the translation string of the given key

public offsetSet (string $offset, string $value)

Sets a translation value

public boolean offsetExists (string $translateKey)

Check whether a translation key exists

public offsetUnset (string $offset)

Elimina un indice del diccionario

public string offsetGet (string $traslateKey)

Returns the translation related to the given key

Class Phalcon\Translate\Adapter\NativeArray

extends Phalcon\Translate\Adapter

implements ArrayAccess, Phalcon\Translate\AdapterInterface

Allows to define translation lists using PHP arrays

Methods

public __construct (unknown $options)

Phalcon\Translate\Adapter\NativeArray constructor

public string query (string $index, array $placeholders)

Returns the translation related to the given key

public bool exists (string $index)

Check whether is defined a translation key in the internal array

public string _ (string $translateKey, array $placeholders) inherited from Phalcon\Translate\Adapter

Returns the translation string of the given key

public offsetSet (string $offset, string $value) inherited from Phalcon\Translate\Adapter

Sets a translation value

public boolean offsetExists (string $translateKey) inherited from Phalcon\Translate\Adapter

Check whether a translation key exists

public offsetUnset (string $offset) inherited from Phalcon\Translate\Adapter

Elimina un indice del diccionario

public string offsetGet (string $traslateKey) inherited from Phalcon\Translate\Adapter

Returns the translation related to the given key

Class Phalcon\Translate\Exception

extends Phalcon\Exception

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct (string $message, int $code, Exception $previous) inherited from Exception

Exception constructor

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Version

This version allows to get version of the framework

Methods

protected static _getVersion ()

Area where the version number is set. The format is as follows: ABBCCDE A - Major version B - Med version (two digits) C - Min version (two digits) D - Special release: 1 = Alpha, 2 = Beta, 3 = RC, 4 = Stable E - Special release version i.e. RC1, Beta2 etc.

public static string get ()

Returns the active version (string)

public static int getId ()

Returns the numeric active version

Interface Phalcon\Acl\AdapterInterface

Phalcon\Acl\AdapterInterface initializer

Methods

abstract public setDefaultAction (int $defaultAccess)

Sets the default access level (Phalcon\Acl::ALLOW or Phalcon\Acl::DENY)

abstract public int getDefaultAction ()

Returns the default ACL access level

abstract public boolean addRole (Phalcon\Acl\RoleInterface $roleObject, array $accessInherits)

Adds a role to the ACL list. Second parameter lets to inherit access data from other existing role

abstract public addInherit (string $roleName, string $roleToInherit)

Do a role inherit from another existing role

abstract public boolean isRole (string $roleName)

Check whether role exist in the roles list

abstract public boolean isResource (string $resourceName)

Check whether resource exist in the resources list

abstract public boolean addResource (Phalcon\Acl\ResourceInterface $resource, unknown $accessList)

Adds a resource to the ACL list Access names can be a particular action, by example search, update, delete, etc or a list of them

abstract public addResourceAccess (string $resourceName, mixed $accessList)

Adds access to resources

abstract public dropResourceAccess (string $resourceName, mixed $accessList)

Removes an access from a resource

abstract public allow (string $roleName, string $resourceName, mixed $access)

Allow access to a role on a resource

abstract public boolean deny (string $roleName, string $resourceName, mixed $access)

Deny access to a role on a resource

abstract public boolean isAllowed (string $role, string $resource, unknown $access)

Check whether a role is allowed to access an action from a resource

abstract public string getActiveRole ()

Returns the role which the list is checking if it’s allowed to certain resource/access

abstract public string getActiveResource ()

Returns the resource which the list is checking if some role can access it

abstract public string getActiveAccess ()

Returns the access which the list is checking if some role can access it

Interface Phalcon\Acl\ResourceInterface

Phalcon\Acl\ResourceInterface initializer

Methods

abstract public __construct (string $name, string $description)

Phalcon\Acl\ResourceInterface constructor

abstract public string getName ()

Returns the resource name

abstract public string getDescription ()

Returns resource description

abstract public string __toString ()

Magic method __toString

Interface Phalcon\Acl\RoleInterface

Phalcon\Acl\RoleInterface initializer

Methods

abstract public __construct (string $name, string $description)

Phalcon\Acl\Role constructor

abstract public string getName ()

Returns the role name

abstract public string getDescription ()

Returns role description

abstract public string __toString ()

Magic method __toString

Interface Phalcon\Cache\BackendInterface

Phalcon\Cache\BackendInterface initializer

Methods

abstract public __construct (Phalcon\Cache\FrontendInterface $frontend, array $options)

Phalcon\Cache\Backend constructor

abstract public mixed start (int|string $keyName)

Starts a cache. The $keyname allows to identify the created fragment

abstract public stop (boolean $stopBuffer)

Stops the frontend without store any cached content

abstract public mixed getFrontend ()

Returns front-end instance adapter related to the back-end

abstract public array getOptions ()

Returns the backend options

abstract public boolean isFresh ()

Checks whether the last cache is fresh or cached

abstract public boolean isStarted ()

Checks whether the cache has starting buffering or not

abstract public setLastKey (string $lastKey)

Sets the last key used in the cache

abstract public string getLastKey ()

Gets the last key stored by the cache

abstract public mixed get (int|string $keyName, long $lifetime)

Returns a cached content

abstract public save (int|string $keyName, string $content, long $lifetime, boolean $stopBuffer)

Stores cached content into the file backend and stops the frontend

abstract public boolean delete (int|string $keyName)

Deletes a value from the cache by its key

abstract public array queryKeys (string $prefix)

Query the existing cached keys

abstract public boolean exists (string $keyName, long $lifetime)

Checks if cache exists and it hasn’t expired

Interface Phalcon\Cache\FrontendInterface

Phalcon\Cache\FrontendInterface initializer

Methods

abstract public int getLifetime ()

Returns the cache lifetime

abstract public boolean isBuffering ()

Check whether if frontend is buffering output

abstract public start ()

Starts the frontend

abstract public string getContent ()

Returns output cached content

abstract public stop ()

Stops the frontend

abstract public beforeStore (mixed $data)

Serializes data before storing it

abstract public afterRetrieve (mixed $data)

Unserializes data after retrieving it

Interface Phalcon\DI\InjectionAwareInterface

Phalcon\DI\InjectionAwareInterface initializer

Methods

abstract public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

abstract public Phalcon\DiInterface getDI ()

Returns the internal dependency injector

Interface Phalcon\DI\ServiceInterface

Phalcon\DI\ServiceInterface initializer

Methods

abstract public __construct (string $name, mixed $definition, boolean $shared)

Phalcon\DI\Service

abstract public getName ()

Returns the service’s name

abstract public setShared (boolean $shared)

Sets if the service is shared or not

abstract public boolean isShared ()

Check whether the service is shared or not

abstract public setDefinition (mixed $definition)

Set the service definition

abstract public mixed getDefinition ()

Returns the service definition

abstract public mixed resolve (unknown $parameters)

Resolves the service

abstract public static Phalcon\DI\Service __set_state (array $attributes)

Restore the interal state of a service

Interface Phalcon\Db\AdapterInterface

Phalcon\Db\AdapterInterface initializer

Methods

abstract public __construct (array $descriptor)

Constructor for Phalcon\Db\Adapter

abstract public array fetchOne (string $sqlQuery, int $fetchMode, int $placeholders)

Returns the first row in a SQL query result

abstract public array fetchAll (string $sqlQuery, int $fetchMode, int $placeholders)

Dumps the complete result of a query into an array

abstract public boolean insert (string $table, array $values, array $fields, array $dataTypes)

Inserts data into a table using custom RBDM SQL syntax

abstract public boolean update (string $table, array $fields, array $values, string $whereCondition, array $dataTypes)

Updates data on a table using custom RBDM SQL syntax

abstract public boolean delete (string $table, string $whereCondition, array $placeholders, array $dataTypes)

Deletes data from a table using custom RBDM SQL syntax

abstract public string getColumnList (array $columnList)

Gets a list of columns

abstract public string limit (string $sqlQuery, int $number)

Appends a LIMIT clause to $sqlQuery argument

abstract public string tableExists (string $tableName, string $schemaName)

Generates SQL checking for the existence of a schema.table

abstract public string viewExists (string $viewName, string $schemaName)

Generates SQL checking for the existence of a schema.view

abstract public string forUpdate (string $sqlQuery)

Returns a SQL modified with a FOR UPDATE clause

abstract public string sharedLock (string $sqlQuery)

Returns a SQL modified with a LOCK IN SHARE MODE clause

abstract public boolean createTable (string $tableName, string $schemaName, array $definition)

Creates a table

abstract public boolean dropTable (string $tableName, string $schemaName, boolean $ifExists)

Drops a table from a schema/database

abstract public boolean addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Adds a column to a table

abstract public boolean modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Modifies a table column based on a definition

abstract public boolean dropColumn (string $tableName, string $schemaName, string $columnName)

Drops a column from a table

abstract public boolean addIndex (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Adds an index to a table

abstract public boolean dropIndex (string $tableName, string $schemaName, string $indexName)

Drop an index from a table

abstract public boolean addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Adds a primary key to a table

abstract public boolean dropPrimaryKey (string $tableName, string $schemaName)

Drops primary key from a table

abstract public boolean true addForeignKey (string $tableName, string $schemaName, Phalcon\Db\ReferenceInterface $reference)

Adds a foreign key to a table

abstract public boolean true dropForeignKey (string $tableName, string $schemaName, string $referenceName)

Drops a foreign key from a table

abstract public string getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Returns the SQL column definition from a column

abstract public array listTables (string $schemaName)

List all tables on a database <code> print_r($connection->listTables(“blog”) ?>

abstract public array getDescriptor ()

Return descriptor used to connect to the active database

abstract public string getConnectionId ()

Gets the active connection unique identifier

abstract public string getSQLStatement ()

Active SQL statement in the object

abstract public string getRealSQLStatement ()

Active SQL statement in the object without replace bound paramters

abstract public array getSQLVariables ()

Active SQL statement in the object

abstract public array getSQLBindTypes ()

Active SQL statement in the object

abstract public string getType ()

Returns type of database system the adapter is used for

abstract public string getDialectType ()

Returns the name of the dialect used

abstract public Phalcon\Db\DialectInterface getDialect ()

Returns internal dialect instance

abstract public boolean connect (array $descriptor)

This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection

abstract public Phalcon\Db\ResultInterface query (string $sqlStatement, array $placeholders, array $dataTypes)

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server return rows

abstract public boolean execute (string $sqlStatement, array $placeholders, array $dataTypes)

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server don’t return any row

abstract public int affectedRows ()

Returns the number of affected rows by the last INSERT/UPDATE/DELETE reported by the database system

abstract public boolean close ()

Closes active connection returning success. Phalcon automatically closes and destroys active connections within Phalcon\Db\Pool

abstract public string escapeIdentifier (string $identifier)

Escapes a column/table/schema name

abstract public string escapeString (string $str)

Escapes a value to avoid SQL injections

abstract public bindParams (unknown $sqlStatement, array $params)

Bind params to a SQL statement

abstract public array convertBoundParams (string $sql, array $params)

Converts bound params like :name: or ?1 into ? bind params

abstract public int lastInsertId (string $sequenceName)

Returns insert id for the auto_increment column inserted in the last SQL statement

abstract public boolean begin ()

Starts a transaction in the connection

abstract public boolean rollback ()

Rollbacks the active transaction in the connection

abstract public boolean commit ()

Commits the active transaction in the connection

abstract public boolean isUnderTransaction ()

Checks whether connection is under database transaction

abstract public PDO getInternalHandler ()

Return internal PDO handler

abstract public Phalcon\Db\IndexInterface [] describeIndexes (string $table, string $schema)

Lists table indexes

abstract public Phalcon\Db\ReferenceInterface [] describeReferences (string $table, string $schema)

Lists table references

abstract public array tableOptions (string $tableName, string $schemaName)

Gets creation options from a table

abstract public Phalcon\Db\RawValue getDefaultIdValue ()

Return the default identity value to insert in an identity column

abstract public boolean supportSequences ()

Check whether the database system requires a sequence to produce auto-numeric values

abstract public Phalcon\Db\ColumnInterface [] describeColumns (string $table, string $schema)

Returns an array of Phalcon\Db\Column objects describing a table

Interface Phalcon\Db\ColumnInterface

Phalcon\Db\ColumnInterface initializer

Methods

abstract public __construct (string $columnName, array $definition)

Phalcon\Db\ColumnInterface constructor

abstract public string getSchemaName ()

Returns schema’s table related to column

abstract public string getName ()

Returns column name

abstract public int getType ()

Returns column type

abstract public int getSize ()

Returns column size

abstract public int getScale ()

Returns column scale

abstract public boolean isUnsigned ()

Returns true if number column is unsigned

abstract public boolean isNotNull ()

Not null

abstract public boolean isPrimary ()

Column is part of the primary key?

abstract public boolean isAutoIncrement ()

Auto-Increment

abstract public boolean isNumeric ()

Check whether column have an numeric type

abstract public boolean isFirst ()

Check whether column have first position in table

abstract public string getAfterPosition ()

Check whether field absolute to position in table

abstract public int getBindType ()

Returns the type of bind handling

abstract public static PhalconDbColumnInterface __set_state (array $data)

Restores the internal state of a Phalcon\Db\Column object

Interface Phalcon\Db\DialectInterface

Phalcon\Db\DialectInterface initializer

Methods

abstract public string limit (string $sqlQuery, int $number)

Generates the SQL for LIMIT clause

abstract public string forUpdate (string $sqlQuery)

Returns a SQL modified with a FOR UPDATE clause

abstract public string sharedLock (string $sqlQuery)

Returns a SQL modified with a LOCK IN SHARE MODE clause

abstract public string select (array $definition)

Builds a SELECT statement

abstract public string getColumnList (array $columnList)

Gets a list of columns

abstract public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Gets the column name in MySQL

abstract public string addColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to add a column to a table

abstract public string modifyColumn (string $tableName, string $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to modify a column in a table

abstract public string dropColumn (string $tableName, string $schemaName, string $columnName)

Generates SQL to delete a column from a table

abstract public string addIndex (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add an index to a table

abstract public string dropIndex (string $tableName, string $schemaName, string $indexName)

Generates SQL to delete an index from a table

abstract public string addPrimaryKey (string $tableName, string $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add the primary key to a table

abstract public string dropPrimaryKey (string $tableName, string $schemaName)

Generates SQL to delete primary key from a table

abstract public string addForeignKey (string $tableName, string $schemaName, Phalcon\Db\ReferenceInterface $reference)

Generates SQL to add an index to a table

abstract public string dropForeignKey (string $tableName, string $schemaName, string $referenceName)

Generates SQL to delete a foreign key from a table

abstract public string createTable (string $tableName, string $schemaName, array $definition)

Generates SQL to create a table

abstract public dropTable (unknown $tableName, unknown $schemaName, unknown $ifExists)

Generates SQL to drop a table

abstract public string tableExists (string $tableName, string $schemaName)

Generates SQL checking for the existence of a schema.table

abstract public string describeColumns (string $table, string $schema)

Generates SQL to describe a table

abstract public array listTables (string $schemaName)

List all tables on database

abstract public string describeIndexes (string $table, string $schema)

Generates SQL to query indexes on a table

abstract public string describeReferences (string $table, string $schema)

Generates SQL to query foreign keys on a table

abstract public string tableOptions (string $table, string $schema)

Generates the SQL to describe the table creation options

Interface Phalcon\Db\IndexInterface

Phalcon\Db\IndexInterface initializer

Methods

abstract public __construct (string $indexName, array $columns)

Phalcon\Db\Index constructor

abstract public string getName ()

Gets the index name

abstract public array getColumns ()

Gets the columns that comprends the index

abstract public static Phalcon\Db\IndexInterface __set_state (array $data)

Restore a Phalcon\Db\Index object from export

Interface Phalcon\Db\ReferenceInterface

Phalcon\Db\ReferenceInterface initializer

Methods

abstract public __construct (string $referenceName, array $definition)

Phalcon\Db\ReferenceInterface constructor

abstract public string getName ()

Gets the index name

abstract public string getSchemaName ()

Gets the schema where referenced table is

abstract public string getReferencedSchema ()

Gets the schema where referenced table is

abstract public array getColumns ()

Gets local columns which reference is based

abstract public string getReferencedTable ()

Gets the referenced table

abstract public array getReferencedColumns ()

Gets referenced columns

abstract public static Phalcon\Db\ReferenceInterface __set_state (array $data)

Restore a Phalcon\Db\Reference object from export

Interface Phalcon\Db\ResultInterface

Phalcon\Db\ResultInterface initializer

Methods

abstract public __construct (Phalcon\Db\AdapterInterface $connection, PDOStatement $result, string $sqlStatement, array $bindParams, array $bindTypes)

Phalcon\Db\Result\Pdo constructor

abstract public boolean execute ()

Allows to executes the statement again. Some database systems don’t support scrollable cursors, So, as cursors are forward only, we need to execute the cursor again to fetch rows from the begining

abstract public mixed fetch ()

Fetches an array/object of strings that corresponds to the fetched row, or FALSE if there are no more rows. This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode

abstract public mixed fetchArray ()

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode

abstract public array fetchAll ()

Returns an array of arrays containing all the records in the result This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode

abstract public int numRows ()

Gets number of rows returned by a resulset

abstract public dataSeek (int $number)

Moves internal resulset cursor to another position letting us to fetch a certain row

abstract public setFetchMode (int $fetchMode)

Changes the fetching mode affecting Phalcon\Db\Result\Pdo::fetch()

abstract public PDOStatement getInternalResult ()

Gets the internal PDO result object

Interface Phalcon\DiInterface

Phalcon\DiInterface initializer

Methods

abstract public Phalcon\Di\ServiceInterface set (string $alias, mixed $config, boolean $shared)

Registers a service in the services container

abstract public Phalcon\Di\ServiceInterface setShared (string $name, mixed $config)

Registers an “always shared” service in the services container

abstract public remove (string $alias)

Removes a service in the services container

abstract public Phalcon\Di\ServiceInterface attempt (string $alias, mixed $config, boolean $shared)

Attempts to register a service in the services container Only is successful if a service hasn’t been registered previously with the same name

abstract public mixed get (string $alias, array $parameters)

Resolves the service based on its configuration

abstract public mixed getShared (string $alias, array $parameters)

Returns a shared service based on their configuration

abstract public mixed getRaw (string $name)

Returns a service definition without resolving

abstract public Phalcon\Di\ServiceInterface getService (unknown $name)

Returns the corresponding Phalcon\Di\Service instance for a service

abstract public boolean has (string $alias)

Check whether the DI contains a service by a name

abstract public boolean wasFreshInstance ()

Check whether the last service obtained via getShared produced a fresh instance or an existing one

abstract public array getServices ()

Return the services registered in the DI

abstract public static setDefault (Phalcon\DiInterface $dependencyInjector)

Set a default dependency injection container to be obtained into static methods

abstract public static Phalcon\DI getDefault ()

Return the last DI created

abstract public static reset ()

Resets the internal default DI

Interface Phalcon\DispatcherInterface

Phalcon\DispatcherInterface initializer

Methods

abstract public setActionSuffix (string $actionSuffix)

Sets the default action suffix

abstract public setDefaultNamespace (string $namespace)

Sets the default namespace

abstract public setDefaultAction (string $actionName)

Sets the default action name

abstract public setActionName (string $actionName)

Sets the action name to be dispatched

abstract public string getActionName ()

Gets last dispatched action name

abstract public setParams (array $params)

Sets action params to be dispatched

abstract public array getParams ()

Gets action params

abstract public setParam (mixed $param, mixed $value)

Set a param by its name or numeric index

abstract public mixed getParam (mixed $param, string|array $filters)

Gets a param by its name or numeric index

abstract public boolean isFinished ()

Checks if the dispatch loop is finished or has more pendent controllers/tasks to disptach

abstract public mixed getReturnedValue ()

Returns value returned by the lastest dispatched action

abstract public object dispatch ()

Dispatches a handle action taking into account the routing parameters

abstract public forward (array $forward)

Forwards the execution flow to another controller/action

Interface Phalcon\EscaperInterface

Phalcon\EscaperInterface initializer

Methods

abstract public setEnconding (string $encoding)

Sets the encoding to be used by the escaper

abstract public string getEncoding ()

Returns the internal encoding used by the escaper

abstract public setHtmlQuoteType (int $quoteType)

Sets the HTML quoting type for htmlspecialchars

abstract public string escapeHtml (string $text)

Escapes a HTML string

abstract public string escapeHtmlAttr (string $text)

Escapes a HTML attribute string

abstract public string escapeCss (string $css)

Escape CSS strings by replacing non-alphanumeric chars by their hexadecimal representation

abstract public string escapeUrl (string $url)

Escapes a URL. Internally uses rawurlencode

Interface Phalcon\Events\EventsAwareInterface

Phalcon\Events\EventsAwareInterface initializer

Methods

abstract public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the events manager

abstract public Phalcon\Events\ManagerInterface getEventsManager ()

Returns the internal event manager

Interface Phalcon\Events\ManagerInterface

Phalcon\Events\ManagerInterface initializer

Methods

abstract public attach (string $eventType, object $handler)

Attach a listener to the events manager

abstract public dettachAll (unknown $type)

Removes all events from the EventsManager

abstract public mixed fire (string $eventType, object $source, mixed $data)

Fires a event in the events manager causing that the acive listeners will be notified about it

abstract public array getListeners (string $type)

Returns all the attached listeners of a certain type

Interface Phalcon\FilterInterface

Phalcon\FilterInterface initializer

Methods

abstract public Phalcon\FilterInterface add (string $name, callable $handler)

Adds a user-defined filter

abstract public mixed sanitize (mixed $value, mixed $filters)

Sanizites a value with a specified single or set of filters

abstract public object[] getFilters ()

Return the user-defined filters in the instance

Interface Phalcon\FlashInterface

Phalcon\FlashInterface initializer

Methods

abstract public string error (string $message)

Shows a HTML error message

abstract public string notice (string $message)

Shows a HTML notice/information message

abstract public string success (string $message)

Shows a HTML success message

abstract public string warning (string $message)

Shows a HTML warning message

abstract public string message (string $type, string $message)

Outputs a message

Interface Phalcon\Http\RequestInterface

Phalcon\Http\RequestInterface initializer

Methods

abstract public mixed get (string $name, string|array $filters, mixed $defaultValue)

Gets a variable from the $_REQUEST superglobal applying filters if needed

abstract public mixed getPost (string $name, string|array $filters, mixed $defaultValue)

Gets a variable from the $_POST superglobal applying filters if needed

abstract public mixed getQuery (string $name, string|array $filters, mixed $defaultValue)

Gets variable from $_GET superglobal applying filters if needed

abstract public mixed getServer (string $name)

Gets variable from $_SERVER superglobal

abstract public boolean has (string $name)

Checks whether $_SERVER superglobal has certain index

abstract public boolean hasPost (string $name)

Checks whether $_POST superglobal has certain index

abstract public boolean hasQuery (string $name)

Checks whether $_SERVER superglobal has certain index

abstract public mixed hasServer (string $name)

Checks whether $_SERVER superglobal has certain index

abstract public string getHeader (string $header)

Gets HTTP header from request data

abstract public string getScheme ()

Gets HTTP schema (http/https)

abstract public boolean isAjax ()

Checks whether request has been made using ajax. Checks if $_SERVER[‘HTTP_X_REQUESTED_WITH’]==’XMLHttpRequest’

abstract public boolean isSoapRequested ()

Checks whether request has been made using SOAP

abstract public boolean isSecureRequest ()

Checks whether request has been made using any secure layer

abstract public string getRawBody ()

Gets HTTP raws request body

abstract public string getServerAddress ()

Gets active server address IP

abstract public string getServerName ()

Gets active server name

abstract public string getHttpHost ()

Gets information about schema, host and port used by the request

abstract public string getClientAddress (boolean $trustForwardedHeader)

Gets most possibly client IPv4 Address. This methods search in $_SERVER[‘REMOTE_ADDR’] and optionally in $_SERVER[‘HTTP_X_FORWARDED_FOR’]

abstract public string getMethod ()

Gets HTTP method which request has been made

abstract public string getUserAgent ()

Gets HTTP user agent used to made the request

abstract public boolean isMethod (string|array $methods)

Check if HTTP method match any of the passed methods

abstract public boolean isPost ()

Checks whether HTTP method is POST. if $_SERVER[‘REQUEST_METHOD’]==’POST’

abstract public boolean isGet ()

Checks whether HTTP method is GET. if $_SERVER[‘REQUEST_METHOD’]==’GET’

abstract public boolean isPut ()

Checks whether HTTP method is PUT. if $_SERVER[‘REQUEST_METHOD’]==’PUT’

abstract public boolean isHead ()

Checks whether HTTP method is HEAD. if $_SERVER[‘REQUEST_METHOD’]==’HEAD’

abstract public boolean isDelete ()

Checks whether HTTP method is DELETE. if $_SERVER[‘REQUEST_METHOD’]==’DELETE’

abstract public boolean isOptions ()

Checks whether HTTP method is OPTIONS. if $_SERVER[‘REQUEST_METHOD’]==’OPTIONS’

abstract public boolean hasFiles ()

Checks whether request include attached files

abstract public Phalcon\Http\Request\FileInterface [] getUploadedFiles ()

Gets attached files as Phalcon\Http\Request\FileInterface compatible instances

abstract public string getHTTPReferer ()

Gets web page that refers active request. ie: http://www.google.com

abstract public array getAcceptableContent ()

Gets array with mime/types and their quality accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT’]

abstract public array getBestAccept ()

Gets best mime/type accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT’]

abstract public array getClientCharsets ()

Gets charsets array and their quality accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_CHARSET’]

abstract public string getBestCharset ()

Gets best charset accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_CHARSET’]

abstract public array getLanguages ()

Gets languages array and their quality accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_LANGUAGE’]

abstract public string getBestLanguage ()

Gets best language accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_LANGUAGE’]

Interface Phalcon\Http\Request\FileInterface

Phalcon\Http\Request\FileInterface initializer

Methods

abstract public __construct (array $file)

Phalcon\Http\Request\FileInterface constructor

abstract public int getSize ()

Returns the file size of the uploaded file

abstract public string getName ()

Returns the real name of the uploaded file

abstract public string getTempName ()

Returns the temporal name of the uploaded file

abstract public boolean moveTo (string $destination)

Move the temporary file to a destination

Interface Phalcon\Http\ResponseInterface

Phalcon\Http\ResponseInterface initializer

Methods

abstract public Phalcon\Http\ResponseInterface setStatusCode (int $code, string $message)

Sets the HTTP response code

abstract public Phalcon\Http\Response\Headers getHeaders ()

Returns headers set by the user

abstract public Phalcon\Http\ResponseInterface setHeader (string $name, string $value)

Overwrites a header in the response

abstract public Phalcon\Http\ResponseInterface setRawHeader (string $header)

Send a raw header to the response

abstract public Phalcon\Http\ResponseInterface resetHeaders ()

Resets all the stablished headers

abstract public Phalcon\Http\ResponseInterface setExpires (DateTime $datetime)

Sets output expire time header

abstract public Phalcon\Http\ResponseInterface setNotModified ()

Sends a Not-Modified response

abstract public Phalcon\Http\ResponseInterface setContentType (string $contentType, string $charset)

Sets the response content-type mime, optionally the charset

abstract public Phalcon\Http\ResponseInterface redirect (string $location, boolean $externalRedirect, int $statusCode)

Redirect by HTTP to another action or URL

abstract public Phalcon\Http\ResponseInterface setContent (string $content)

Sets HTTP response body

abstract public Phalcon\Http\ResponseInterface appendContent (string $content)

Appends a string to the HTTP response body

abstract public string getContent ()

Gets the HTTP response body

abstract public Phalcon\Http\ResponseInterface sendHeaders ()

Sends headers to the client

abstract public Phalcon\Http\ResponseInterface send ()

Prints out HTTP response to the client

Interface Phalcon\Http\Response\HeadersInterface

Phalcon\Http\Response\HeadersInterface initializer

Methods

abstract public set (string $name, string $value)

Sets a header to be sent at the end of the request

abstract public string get (string $name)

Gets a header value from the internal bag

abstract public setRaw (string $header)

Sets a raw header to be sent at the end of the request

abstract public boolean send ()

Sends the headers to the client

abstract public reset ()

Reset set headers

abstract public static Phalcon\Http\Response\HeadersInterface __set_state (unknown $data)

Restore a Phalcon\Http\Response\Headers object

Interface Phalcon\Logger\AdapterInterface

Phalcon\Logger\AdapterInterface initializer

Methods

abstract public setFormat (string $format)

Set the log format

abstract public format getFormat ()

Returns the log format

abstract public string getTypeString (integer $type)

Returns the string meaning of a logger constant

abstract public setDateFormat (string $date)

Sets the internal date format

abstract public string getDateFormat ()

Returns the internal date format

abstract public log (string $message, int $type)

Sends/Writes messages to the file log

abstract public begin ()

Starts a transaction

abstract public commit ()

Commits the internal transaction

abstract public rollback ()

Rollbacks the internal transaction

abstract public boolean close ()

Closes the logger

abstract public debug (string $message)

Sends/Writes a debug message to the log

abstract public error (string $message)

Sends/Writes an error message to the log

abstract public info (string $message)

Sends/Writes an info message to the log

abstract public notice (string $message)

Sends/Writes a notice message to the log

abstract public warning (string $message)

Sends/Writes a warning message to the log

abstract public alert (string $message)

Sends/Writes an alert message to the log

Interface Phalcon\Mvc\ControllerInterface

Interface Phalcon\Mvc\DispatcherInterface

Phalcon\Mvc\DispatcherInterface initializer

Methods

abstract public setControllerSuffix (string $controllerSuffix)

Sets the default controller suffix

abstract public setDefaultController (string $controllerName)

Sets the default controller name

abstract public setControllerName (string $controllerName)

Sets the controller name to be dispatched

abstract public string getControllerName ()

Gets last dispatched controller name

abstract public Phalcon\Mvc\ControllerInterface getLastController ()

Returns the lastest dispatched controller

abstract public Phalcon\Mvc\ControllerInterface getActiveController ()

Returns the active controller in the dispatcher

Interface Phalcon\Mvc\ModelInterface

Phalcon\Mvc\ModelInterface initializer

Methods

abstract public __construct (Phalcon\DiInterface $dependencyInjector, string $managerService, string $dbService)

Phalcon\Mvc\Model constructor

abstract public Phalcon\Mvc\ModelInterface setTransaction (Phalcon\Mvc\Model\TransactionInterface $transaction)

Sets a transaction related to the Model instance

abstract public string getSource ()

Returns table name mapped in the model

abstract public string getSchema ()

Returns schema name where table mapped is located

abstract public setConnectionService (string $connectionService)

Sets the DependencyInjection connection service

abstract public string getConnectionService ()

Returns DependencyInjection connection service

abstract public Phalcon\Db\AdapterInterface getConnection ()

Gets internal database connection

abstract public static Phalcon\Mvc\ModelInterface $result dumpResult (Phalcon\Mvc\ModelInterface $base, array $result)

Assigns values to a model from an array returning a new model

abstract public static Phalcon\Mvc\Model\ResultsetInterface find (array $parameters)

Allows to query a set of records that match the specified conditions

abstract public static Phalcon\Mvc\ModelInterface findFirst (array $parameters)

Allows to query the first record that match the specified conditions

abstract public static Phalcon\Mvc\Model\CriteriaInterface query (unknown $dependencyInjector)

Create a criteria for a especific model

abstract public static int count (array $parameters)

Allows to count how many records match the specified conditions

abstract public static double sum (array $parameters)

Allows to a calculate a summatory on a column that match the specified conditions

abstract public static mixed maximum (array $parameters)

Allows to get the maximum value of a column that match the specified conditions

abstract public static mixed minimum (array $parameters)

Allows to get the minimum value of a column that match the specified conditions

abstract public static double average (array $parameters)

Allows to calculate the average value on a column matching the specified conditions

abstract public appendMessage (Phalcon\Mvc\Model\MessageInterface $message)

Appends a customized message on the validation process

abstract public boolean validationHasFailed ()

Check whether validation process has generated any messages

abstract public Phalcon\Mvc\Model\MessageInterface [] getMessages ()

Returns all the validation messages

abstract public boolean save (array $data)

Inserts or updates a model instance. Returning true on success or false otherwise.

abstract public boolean create (array $data)

Inserts a model instance. If the instance already exists in the persistance it will throw an exception Returning true on success or false otherwise.

abstract public boolean update (array $data)

Updates a model instance. If the instance doesn’t exist in the persistance it will throw an exception Returning true on success or false otherwise.

abstract public boolean delete ()

Deletes a model instance. Returning true on success or false otherwise.

abstract public int getOperationMade ()

Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants

abstract public mixed readAttribute (string $attribute)

Reads an attribute value by its name

abstract public writeAttribute (string $attribute, mixed $value)

Writes an attribute value by its name

abstract public Phalcon\Mvc\Model\ResultsetInterface getRelated (string $modelName, array $arguments)

Returns related records based on defined relations

Interface Phalcon\Mvc\Model\CriteriaInterface

Phalcon\Mvc\Model\CriteriaInterface initializer

Methods

abstract public Phalcon\Mvc\Model\CriteriaInterface setModelName (string $modelName)

Set a model on which the query will be executed

abstract public string getModelName ()

Returns an internal model name on which the criteria will be applied

abstract public Phalcon\Mvc\Model\CriteriaInterface bind (string $bindParams)

Adds the bind parameter to the criteria

abstract public Phalcon\Mvc\Model\CriteriaInterface where (string $conditions)

Adds the conditions parameter to the criteria

abstract public Phalcon\Mvc\Model\CriteriaInterface conditions (string $conditions)

Adds the conditions parameter to the criteria

abstract public Phalcon\Mvc\Model\CriteriaInterface order (string $orderColumns)

Adds the order-by parameter to the criteria

abstract public Phalcon\Mvc\Model\CriteriaInterface limit (int $limit, int $offset)

Adds the limit parameter to the criteria

abstract public Phalcon\Mvc\Model\CriteriaInterface forUpdate (boolean $forUpdate)

Adds the “for_update” parameter to the criteria

abstract public Phalcon\Mvc\Model\Criteria sharedLock (boolean $sharedLock)

Adds the “shared_lock” parameter to the criteria

abstract public string getWhere ()

Returns the conditions parameter in the criteria

abstract public string getConditions ()

Returns the conditions parameter in the criteria

abstract public string getLimit ()

Returns the limit parameter in the criteria

abstract public string getOrder ()

Returns the order parameter in the criteria

abstract public string getParams ()

Returns all the parameters defined in the criteria

abstract public static fromInput (Phalcon\DiInterface $dependencyInjector, string $modelName, array $data)

Builds a Phalcon\Mvc\Model\Criteria based on an input array like $_POST

abstract public Phalcon\Mvc\Model\ResultsetInterface execute ()

Executes a find using the parameters built with the criteria

Interface Phalcon\Mvc\Model\ManagerInterface

Phalcon\Mvc\Model\ManagerInterface initializer

Methods

abstract public initialize (Phalcon\Mvc\ModelInterface $model)

Initializes a model in the model manager

abstract public boolean isInitialized (string $modelName)

Check of a model is already initialized

abstract public Phalcon\Mvc\ModelInterface getLastInitialized ()

Get last initialized model

abstract public Phalcon\Mvc\ModelInterface load (unknown $modelName)

Loads a model throwing an exception if it doesn’t exist

abstract public addHasOne (Phalcon\Mvc\ModelInterface $model, mixed $fields, string $referenceModel, mixed $referencedFields, array $options)

Setup a 1-1 relation between two models

abstract public addBelongsTo (Phalcon\Mvc\ModelInterface $model, mixed $fields, string $referenceModel, mixed $referencedFields, array $options)

Setup a relation reverse 1-1 between two models

abstract public addHasMany (Phalcon\Mvc\ModelInterface $model, mixed $fields, string $referenceModel, mixed $referencedFields, array $options)

Setup a relation 1-n between two models

abstract public boolean existsBelongsTo (string $modelName, string $modelRelation)

Checks whether a model has a belongsTo relation with another model

abstract public boolean existsHasMany (string $modelName, string $modelRelation)

Checks whether a model has a hasMany relation with another model

abstract public boolean existsHasOne (string $modelName, string $modelRelation)

Checks whether a model has a hasOne relation with another model

abstract public Phalcon\Mvc\Model\ResultsetInterface getBelongsToRecords (string $method, string $modelName, string $modelRelation, Phalcon\Mvc\Model $record, array $parameters)

Gets belongsTo related records from a model

abstract public Phalcon\Mvc\Model\ResultsetInterface getHasManyRecords (string $method, string $modelName, string $modelRelation, Phalcon\Mvc\Model $record, array $parameters)

Gets hasMany related records from a model

abstract public Phalcon\Mvc\Model\ResultsetInterface getHasOneRecords (string $method, string $modelName, string $modelRelation, Phalcon\Mvc\Model $record, array $parameters)

Gets belongsTo related records from a model

abstract public array getBelongsTo (Phalcon\Mvc\ModelInterface $model)

Gets belongsTo relations defined on a model

abstract public array getHasMany (Phalcon\Mvc\ModelInterface $model)

Gets hasMany relations defined on a model

abstract public array getHasOne (Phalcon\Mvc\ModelInterface $model)

Gets hasOne relations defined on a model

abstract public array getHasOneAndHasMany (Phalcon\Mvc\ModelInterface $model)

Gets hasOne relations defined on a model

abstract public array getRelations (string $first, string $second)

Query the relations between two models

abstract public Phalcon\Mvc\Model\QueryInterface createQuery (string $phql)

Creates a Phalcon\Mvc\Model\Query without execute it

abstract public Phalcon\Mvc\Model\QueryInterface executeQuery (string $phql, array $placeholders)

Creates a Phalcon\Mvc\Model\Query and execute it

Interface Phalcon\Mvc\Model\MessageInterface

Phalcon\Mvc\Model\MessageInterface initializer

Methods

abstract public __construct (string $message, string $field, string $type)

Phalcon\Mvc\Model\Message constructor

abstract public setType (string $type)

Sets message type

abstract public string getType ()

Returns message type

abstract public setMessage (string $message)

Sets verbose message

abstract public string getMessage ()

Returns verbose message

abstract public setField (string $field)

Sets field name related to message

abstract public string getField ()

Returns field name related to message

abstract public string __toString ()

Magic __toString method returns verbose message

abstract public static Phalcon\Mvc\Model\MessageInterface __set_state (array $message)

Magic __set_state helps to recover messsages from serialization

Interface Phalcon\Mvc\Model\MetaDataInterface

Phalcon\Mvc\Model\MetaDataInterface initializer

Methods

abstract public array readMetaData (Phalcon\Mvc\ModelInterface $model)

Reads meta-data for certain model

abstract public mixed readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, int $index)

Reads meta-data for certain model using a MODEL_* constant

abstract public writeMetaDataIndex (Phalcon\Mvc\Model $model, int $index, mixed $data)

Writes meta-data for certain model using a MODEL_* constant

abstract public array readColumnMap (Phalcon\Mvc\ModelInterface $model)

Reads the ordered/reversed column map for certain model

abstract public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, int $index)

Reads column-map information for certain model using a MODEL_* constant

abstract public array getAttributes (Phalcon\Mvc\ModelInterface $model)

Returns table attributes names (fields)

abstract public array getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model)

Returns an array of fields which are part of the primary key

abstract public array getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model)

Returns an arrau of fields which are not part of the primary key

abstract public array getNotNullAttributes (Phalcon\Mvc\ModelInterface $model)

Returns an array of not null attributes

abstract public array getDataTypes (Phalcon\Mvc\ModelInterface $model)

Returns attributes and their data types

abstract public array getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model)

Returns attributes which types are numerical

abstract public string getIdentityField (Phalcon\Mvc\ModelInterface $model)

Returns the name of identity field (if one is present)

abstract public array getBindTypes (Phalcon\Mvc\ModelInterface $model)

Returns attributes and their bind data types

abstract public array getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model)

Returns attributes that must be ignored from the INSERT SQL generation

abstract public array getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model)

Returns attributes that must be ignored from the UPDATE SQL generation

abstract public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

Set the attributes that must be ignored from the INSERT SQL generation

abstract public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

Set the attributes that must be ignored from the UPDATE SQL generation

abstract public array getColumnMap (Phalcon\Mvc\ModelInterface $model)

Returns the column map if any

abstract public array getReverseColumnMap (Phalcon\Mvc\ModelInterface $model)

Returns the reverse column map if any

abstract public boolean hasAttribute (Phalcon\Mvc\ModelInterface $model, unknown $attribute)

Check if a model has certain attribute

abstract public boolean isEmpty ()

Checks if the internal meta-data container is empty

abstract public reset ()

Resets internal meta-data in order to regenerate it

abstract public array read (unknown $key)

Reads meta-data from the adapter

abstract public write (string $key, array $data)

Writes meta-data to the adapter

Interface Phalcon\Mvc\Model\QueryInterface

Phalcon\Mvc\Model\QueryInterface initializer

Methods

abstract public __construct (string $phql)

Phalcon\Mvc\Model\Query constructor

abstract public array parse ()

Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another intermediate representation that could be executed by Phalcon\Mvc\Model\Query

abstract public mixed execute (array $bindParams, array $bindTypes)

Executes a parsed PHQL statement

Interface Phalcon\Mvc\Model\Query\StatusInterface

Phalcon\Mvc\Model\Query\StatusInterface initializer

Methods

abstract public __construct (boolean $success, Phalcon\Mvc\ModelInterface $model)

Phalcon\Mvc\Model\Query\Status

abstract public Phalcon\Mvc\ModelInterface getModel ()

Returns the model which executed the action

abstract public Phalcon\Mvc\Model\MessageInterface [] getMessages ()

Returns the messages produced by a operation failed

abstract public boolean success ()

Allows to check if the executed operation was successful

Interface Phalcon\Mvc\Model\ResultInterface

Phalcon\Mvc\Model\ResultInterface initializer

Methods

abstract public setForceExists (boolean $forceExists)

Forces that a model doesn’t need to be checked if exists before store it

Interface Phalcon\Mvc\Model\ResultsetInterface

Phalcon\Mvc\Model\ResultsetInterface initializer

Methods

abstract public Phalcon\Mvc\ModelInterface getFirst ()

Get first row in the resultset

abstract public Phalcon\Mvc\ModelInterface getLast ()

Get last row in the resultset

abstract public setIsFresh (boolean $isFresh)

Set if the resultset is fresh or an old one cached

abstract public boolean isFresh ()

Tell if the resultset if fresh or an old one cached

abstract public Phalcon\Cache\BackendInterface getCache ()

Returns the associated cache for the resultset

Interface Phalcon\Mvc\Model\TransactionInterface

Phalcon\Mvc\Model\TransactionInterface initializer

Methods

abstract public __construct (Phalcon\DiInterface $dependencyInjector, boolean $autoBegin)

Phalcon\Mvc\Model\Transaction constructor

abstract public setTransactionManager (Phalcon\Mvc\Model\Transaction\ManagerInterface $manager)

Sets transaction manager related to the transaction

abstract public boolean begin ()

Starts the transaction

abstract public boolean commit ()

Commits the transaction

abstract public boolean rollback (string $rollbackMessage, Phalcon\Mvc\ModelInterface $rollbackRecord)

Rollbacks the transaction

abstract public string getConnection ()

Returns connection related to transaction

abstract public setIsNewTransaction (boolean $isNew)

Sets if is a reused transaction or new once

abstract public setRollbackOnAbort (boolean $rollbackOnAbort)

Sets flag to rollback on abort the HTTP connection

abstract public boolean isManaged ()

Checks whether transaction is managed by a transaction manager

abstract public array getMessages ()

Returns validations messages from last save try

abstract public boolean isValid ()

Checks whether internal connection is under an active transaction

abstract public setRollbackedRecord (Phalcon\Mvc\ModelInterface $record)

Sets object which generates rollback action

Interface Phalcon\Mvc\Model\Transaction\ManagerInterface

Phalcon\Mvc\Model\Transaction\ManagerInterface initializer

Methods

abstract public __construct (Phalcon\DiInterface $dependencyInjector)

Phalcon\Mvc\Model\Transaction\Manager

abstract public boolean has ()

Checks whether manager has an active transaction

abstract public Phalcon\Mvc\Model\TransactionInterface get (boolean $autoBegin)

Returns a new Phalcon\Mvc\Model\Transaction or an already created once

abstract public rollbackPendent ()

Rollbacks active transactions within the manager

abstract public commit ()

Commmits active transactions within the manager

abstract public rollback (boolean $collect)

Rollbacks active transactions within the manager Collect will remove transaction from the manager

abstract public notifyRollback (Phalcon\Mvc\Model\TransactionInterface $transaction)

Notifies the manager about a rollbacked transaction

abstract public notifyCommit (Phalcon\Mvc\Model\TransactionInterface $transaction)

Notifies the manager about a commited transaction

abstract public collectTransactions ()

Remove all the transactions from the manager

Interface Phalcon\Mvc\Model\ValidatorInterface

Phalcon\Mvc\Model\ValidatorInterface initializer

Methods

abstract public array getMessages ()

Returns messages generated by the validator

abstract public boolean validate (Phalcon\Mvc\ModelInterface $record)

Executes the validator

Interface Phalcon\Mvc\ModuleDefinitionInterface

Phalcon\Mvc\ModuleDefinitionInterface initializer

Methods

abstract public registerAutoloaders ()

Registers an autoloader related to the module

abstract public registerServices (Phalcon\DiInterface $dependencyInjector)

Registers an autoloader related to the module

Interface Phalcon\Mvc\RouterInterface

Phalcon\Mvc\RouterInterface initializer

Methods

abstract public setDefaultModule (string $moduleName)

Sets the name of the default module

abstract public setDefaultController (string $controllerName)

Sets the default controller name

abstract public setDefaultAction (string $actionName)

Sets the default action name

abstract public setDefaults (array $defaults)

Sets an array of default paths

abstract public handle (string $uri)

Handles routing information received from the rewrite engine

abstract public Phalcon\Mvc\Router\RouteInterface add (string $pattern, string/array $paths, string $httpMethods)

Adds a route to the router on any HTTP method

abstract public Phalcon\Mvc\Router\RouteInterface addGet (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is GET

abstract public Phalcon\Mvc\Router\RouteInterface addPost (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is POST

abstract public Phalcon\Mvc\Router\RouteInterface addPut (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is PUT

abstract public Phalcon\Mvc\Router\RouteInterface addDelete (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is DELETE

abstract public Phalcon\Mvc\Router\RouteInterface addOptions (string $pattern, string/array $paths)

Add a route to the router that only match if the HTTP method is OPTIONS

abstract public Phalcon\Mvc\Router\RouteInterface addHead (string $pattern, string/array $paths)

Adds a route to the router that only match if the HTTP method is HEAD

abstract public clear ()

Removes all the defined routes

abstract public string getModuleName ()

Returns processed module name

abstract public string getControllerName ()

Returns processed controller name

abstract public string getActionName ()

Returns processed action name

abstract public array getParams ()

Returns processed extra params

abstract public Phalcon\Mvc\Router\RouteInterface getMatchedRoute ()

Returns the route that matchs the handled URI

abstract public array getMatches ()

Return the sub expressions in the regular expression matched

abstract public bool wasMatched ()

Check if the router macthes any of the defined routes

abstract public Phalcon\Mvc\Router\RouteInterface [] getRoutes ()

Return all the routes defined in the router

abstract public Phalcon\Mvc\Router\RouteInterface getRouteById (unknown $id)

Returns a route object by its id

abstract public Phalcon\Mvc\Router\RouteInterface getRouteByName (unknown $name)

Returns a route object by its name

Interface Phalcon\Mvc\Router\RouteInterface

Phalcon\Mvc\Router\RouteInterface initializer

Methods

abstract public __construct (string $pattern, array $paths, array|string $httpMethods)

Phalcon\Mvc\Router\Route constructor

abstract public string compilePattern (string $pattern)

Replaces placeholders from pattern returning a valid PCRE regular expression

abstract public via (string|array $httpMethods)

Set one or more HTTP methods that constraint the matching of the route

abstract public reConfigure (string $pattern, array $paths)

Reconfigure the route adding a new pattern and a set of paths

abstract public string getName ()

Returns the route’s name

abstract public setName (string $name)

Sets the route’s name

abstract public setHttpMethods (string|array $httpMethods)

Sets a set of HTTP methods that constraint the matching of the route

abstract public string getRouteId ()

Returns the route’s id

abstract public string getPattern ()

Returns the route’s pattern

abstract public string getCompiledPattern ()

Returns the route’s pattern

abstract public array getPaths ()

Returns the paths

abstract public string|array getHttpMethods ()

Returns the HTTP methods that constraint matching the route

abstract public static reset ()

Resets the internal route id generator

Interface Phalcon\Mvc\UrlInterface

Phalcon\Mvc\UrlInterface initializer

Methods

abstract public setBaseUri (string $baseUri)

Sets a prefix to all the urls generated

abstract public string getBaseUri ()

Returns the prefix for all the generated urls. By default /

abstract public setBasePath (string $basePath)

Sets a base paths for all the generated paths

abstract public string getBasePath ()

Returns a base path

abstract public string get (string|array $uri)

Generates a URL

abstract public string path (string $path)

Generates a local path

Interface Phalcon\Mvc\ViewInterface

Phalcon\Mvc\ViewInterface initializer

Methods

abstract public setViewsDir (string $viewsDir)

Sets views directory. Depending of your platform, always add a trailing slash or backslash

abstract public string getViewsDir ()

Gets views directory

abstract public setBasePath (string $basePath)

Sets base path. Depending of your platform, always add a trailing slash or backslash

abstract public setRenderLevel (string $level)

Sets the render level for the view

abstract public setMainView (unknown $viewPath)

Sets default view name. Must be a file without extension in the views directory

abstract public setTemplateBefore (string|array $templateBefore)

Appends template before controller layout

abstract public cleanTemplateBefore ()

Resets any template before layouts

abstract public setTemplateAfter (string|array $templateAfter)

Appends template after controller layout

abstract public cleanTemplateAfter ()

Resets any template before layouts

abstract public setParamToView (string $key, mixed $value)

Adds parameters to views (alias of setVar)

abstract public setVar (string $key, mixed $value)

Adds parameters to views

abstract public array getParamsToView ()

Returns parameters to views

abstract public string getControllerName ()

Gets the name of the controller rendered

abstract public string getActionName ()

Gets the name of the action rendered

abstract public array getParams ()

Gets extra parameters of the action rendered

abstract public start ()

Starts rendering process enabling the output buffering

abstract public registerEngines (array $engines)

Register templating engines

abstract public render (string $controllerName, string $actionName, array $params)

Executes render process from dispatching data

abstract public pick (string $renderView)

Choose a view different to render than last-controller/last-action

abstract public string partial (string $partialPath)

Renders a partial view

abstract public finish ()

Finishes the render process by stopping the output buffering

abstract public Phalcon\Cache\BackendInterface getCache ()

Returns the cache instance used to cache

abstract public cache (boolean|array $options)

Cache the actual view render to certain level

abstract public setContent (string $content)

Externally sets the view content

abstract public string getContent ()

Returns cached ouput from another view stage

abstract public string getActiveRenderPath ()

Returns the path of the view that is currently rendered

abstract public disable ()

Disables the auto-rendering process

abstract public enable ()

Enables the auto-rendering process

abstract public reset ()

Resets the view component to its factory default values

Interface Phalcon\Mvc\View\EngineInterface

Phalcon\Mvc\View\EngineInterface initializer

Methods

abstract public __construct (Phalcon\Mvc\ViewInterface $view, Phalcon\DiInterface $dependencyInjector)

Phalcon\Mvc\View\Engine constructor

abstract public array getContent ()

Returns cached ouput on another view stage

abstract public string partial (string $partialPath)

Renders a partial inside another view

abstract public render (string $path, array $params, boolean $mustClean)

Renders a view using the template engine

Interface Phalcon\Paginator\AdapterInterface

Phalcon\Paginator\AdapterInterface initializer

Methods

abstract public __construct (array $config)

Phalcon\Paginator\AdapterInterface constructor

abstract public setCurrentPage (int $page)

Set the current page number

abstract public stdClass getPaginate ()

Returns a slice of the resultset to show in the pagination

Interface Phalcon\Session\AdapterInterface

Phalcon\Session\AdapterInterface initializer

Methods

abstract public __construct (array $options)

Phalcon\Session construtor

abstract public start ()

Starts session, optionally using an adapter

abstract public setOptions (array $options)

Sets session options

abstract public array getOptions ()

Get internal options

abstract public get (string $index)

Gets a session variable from an application context

abstract public set (string $index, string $value)

Sets a session variable in an application context

abstract public has (string $index)

Check whether a session variable is set in an application context

abstract public remove (string $index)

Removes a session variable from an application context

abstract public string getId ()

Returns active session id

abstract public boolean isStarted ()

Check whether the session has been started

abstract public boolean destroy ()

Destroys the active session

Interface Phalcon\Session\BagInterface

Phalcon\Session\BagInterface initializer

Methods

abstract public initialize ()

Initializes the session bag. This method must not be called directly, the class calls it when its internal data is accesed

abstract public destroy ()

Destroyes the session bag

abstract public __set (string $property, string $value)

Setter of values

abstract public string __get (string $property)

Getter of values

abstract public boolean __isset (string $property)

Isset property

Interface Phalcon\Translate\AdapterInterface

Phalcon\Translate\AdapterInterface initializer

Methods

abstract public __construct (unknown $options)

Phalcon\Translate\Adapter\NativeArray constructor

abstract public string _ (string $translateKey, array $placeholders)

Returns the translation string of the given key

abstract public string query (string $index, array $placeholders)

Returns the translation related to the given key

abstract public bool exists (string $index)

Check whether is defined a translation key in the internal array

License

Phalcon is brought to you by the Phalcon Team! [Twitter - Google Plus - Github]

The Phalcon PHP Framework is released under the new BSD license. Except where otherwise noted, content on this site is licensed under the Creative Commons Attribution 3.0 License.

If you love Phalcon please return something to the community! :)

其他格式