linux环境下安装: ( 编译安装 ) --- 本人使用的是 ubuntu 哟!!!
Phalcon是一个用C实现的扩展,所以您可以下载适合您机器的二进制格式文件或者使用源代码进行编译。
sudo apt-add-repository ppa:phalcon/stable
sudo apt-get update
sudo apt-get install php5-phalcon
如果你没有apt-add-repository请执行以下command:
sudo apt-get install python-software-properties
Linux下,使用源代码编译安装是很方便的。
安装要求
我们需要提前安装一些库:
#Ubuntu
sudo apt-get install php5-dev php5-mysql gcc libpcre3-dev
编译
1. 从C源代码创建扩展请按照下面的步骤:
git clone --depth=1 git://github.com/phalcon/cphalcon.git
cd cphalcon/build sudo
./install
2. 添加扩展到php.ini文件:
extension=phalcon.so
3. 最后,重启web服务器
上面装好过后在命令行里面创建项目的命令还没有需要安装开发工具
这些工具是一些有用的脚本,用于生成结构性的代码。 您应用的核心代码只需要用一句简单的命令即可生成, 让您更加方便地使用Phalcon去开发应用。
安装composer到一个公用的位置或在您的项目里面:
curl -s http://getcomposer.org/installer | php
根据下面代码创建composer.json文件:
{ "require": { "phalcon/devtools": "dev-master" } }
运行composer安装器:
php composer.phar install
给phalcon.php创建symbolic link:
ln -s ~/devtools/phalcon.php /usr/bin/phalcon
chmod ugo+x /usr/bin/phalcon
扩展:
git clone --depth=1 git://github.com/phalcon/cphalcon.git ----------- 必须先安装 git 工具 然后进入目录 执行 sudo ./install 安装成功
使用 git 工具下载开发者工具 进入文件夹之后运行
ln -s ~/phalcon-devtools/phalcon.php /usr/bin/phalcon
chmod ugo+x /usr/bin/phalcon
配置nginx
server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /www; index index.php index.html index.htm; # Make site accessible from http://localhost/ server_name localhost; location ~ .php$ { try_files $uri =404; #增加 fastcgi_split_path_info ^(.+.php)(/.+)$; #反注释 ## NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini # ## With php5-cgi alone: # fastcgi_pass 127.0.0.1:9000; ## With php5-fpm: fastcgi_pass unix:/var/run/php5-fpm.sock; #反注释 fastcgi_index index.php; #反注释 include fastcgi_params; #反注释 } server { listen 80; server_name www.test.me; set $root_path '/www/maple/leon/phalcon/test/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 unix:/var/run/php5-fpm.sock; 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; } }
---- 这里是执行添加环境变量功能。
命令行功能的操作
Available commands:
别名列表,列举:commands
创建控制器 controller -> controller [name] [directory]
Options: --name=s Controller name --namespace=s Controller's namespace [option] --directory=s Directory where the controller should be created [optional] --base-class=s Base class to be inherited by the controller [optional] --force Force to rewrite controller [optional]
phalcon controller 控制器名称
创建模型 model
phalcon model 表名(必须和数据库表名一致)
创建所有表名 all-models
phalcon all-models
创建项目 project -> project [name] [type] [directory] [enable-webtools]
Options: --name Name of the new project --enable-webtools Determines if webtools should be enabled [optional] --directory=s Base path on which project will be created [optional] --type=s Type of the application to be generated (micro, simple, modules) --template-path Specify a template path [optional] --use-config-ini Use a ini file as configuration file [optional] --trace Shows the trace of the framework in case of exception. [optional] --help Shows this help
phalcon project 项目名称
phalcon project 项目名称 --type modules (创建控制器的时候没有创建命令空间,需要自己添加/contoller/Action)
创建数据库表的支架 scaffold
使用:scaffold [tableName] [options]
Options: --table-name=s Table used as base to generate the scaffold --schema=s Name of the schema. [optional] --get-set Attributes will be protected and have setters/getters. [optional] --directory=s Base path on which project was created [optional] --template-path=s Specify a template path [optional] --template-engine=s Define the template engine, default php (php, volt). [optional] --force Forces to rewrite generated code if they already exists. [optional] --trace Shows the trace of the framework in case of exception. [optional] --ns-models=s Model's namespace [optional] --ns-controllers=s Controller's namespace [optional]
migration
webtools
创建表的脚手架
phalcon scaffold --table-name 表名
//控制控制器输出 $this->view->disable();
1 URL重定向:
重定向用来在当前的处理中跳转到其它的处理流:
<?php
___重定向不会禁用视图组件。因此,如果你想从一个controller/action重定向到另一个controller/acton上,视图将正常显示。当然,你也可以使用 $this->view->disable() 禁用视图输出。
2 存储/获取 Session数据
$this->session->set("session_name", "session_value");
$this->session->has("session-name");
$this->session->get("session-name");
$this->session->remove("session-name");
$this->session->destroy();
3 数据库操作方法
添加 直接设置传递过来的值即可 或可以使用save()方法
更新 save()
删除 delete()
查找 find() findFirst()
保存 save()
4 From 表单接收
eg:$name= $this->request->getPost("name", "string");
$email =$this->request->getPost("email", "email");
从容器中获取的服务的最简单方式就是只用get方法,它将从容器中返回一个新的实例:
或者通过下面这种魔术方法的形式调用:
5 控制器跳转
在控制器中做跳转操作,一般会用到 dispatcher的 forward方法
$this->dispatcher->forward(array(
"controller" => "users",
"action" => "signin"
));
也可以定义beaseController 自定义方法进行控制器的跳转。
6 处理Not-Found
当用户访问未定义的路由时, 微应用会试着执行 "Not-Found"处理器。
7 中文乱码问题
1、先把utf8换成gbk试试
'charset'
=>
'gbk'
2、或者不用charset,使用
'options' => array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8') 这样试试。
8 数据库操作
findFirst()
使用方法:$xxx = 表名::findFirst(); $this->view->setVar('name(参数)',$region->name(字段名)); 更改数据 $region->name = "数据"; $region->save(); //sql 什么字段下什么数据 $region = Users::findFirst("字段='数据'"); //sql语句的拼接 $region = Users::findFirst(array("字段='数据'","order"=>"name"));
find
//数据表总共有多是条数据 $user = Users::find();echo count($user); //xx字段xx数据有多少个 $user = Users::find("xx = 'xx'");echo count($user); //打印字段的数据(这里面主要做的是sql语句的拼接:这一句就好比(SELECT (Users) * FROM Users WHERE 字段 = '数据' ORDER BY name)) $user = Users::find(array( "字段 = '数据'", "order" => "name" //如果还需要拼接可以接着写 "limit" => 100 //多少条 limit 100 )); foreach($user as $r){ echo $r->字段,"\n"; }
foreach($user as $u){ //遍历所有的xx字段数据 echo $u->name, "<br/>"; } $user->rewind(); while ($user->valid()) { $robot = $user->current(); echo $robot->name, "<br/>"; $user->next(); } //总数 echo count($user); echo $user->count(); //把数据存到一个文件中 file_put_contents("cache.txt", serialize($user));
可用查询选项:
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\Mvc\Model assumes the first parameter are the conditions. | “conditions” => “name LIKE ‘steve%’” |
columns | Return specific columns instead of the full columns in the model. When using this option an incomplete object is returned | “columns” => “id, name” |
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 / “limit” => array(“number” => 10, “offset” => 5) |
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 resultset, reducing the continuous access to the relational system | “cache” => array(“lifetime” => 3600, “key” => “my-find-key”) |
hydration | Sets the hydration strategy to represent each returned record in the result | “hydration” => Resultset::HYDRATE_OBJECTS |
//这个方式看起来更加直观,这是一种面向对象的构建查询的方式,execute()执行后返回ResultSet
$robots = Robots::query() ->where("type = :type:") ->andWhere("year < 2000") ->bind(array("type" => "mechanical")) ->order("name") ->execute();
注意:find和findFirst方法是只能针对当模型操作,没有join操作,涉及多表操作时,一、可以依赖模型间的关系定义,自动完成;二、使用query()构建查询,三、使用Phalcon\Mvc\Query执行PQHL查询 四、使用Phalcon\Mvc\Query\Builder来构建PHQL查询语句然后执行;一般如果涉及多表查询,如果模型间的关系定义无法满足时(比如left join等),可以使用模型的query()方法构建查询并把逻辑封装在模型内部。
所有查询先构建成PHQL查询,然后再翻译成具体数据库的SQL。
//字段里面数据的所有数据 $name = "helinfeng"; $robot = Users::findFirstByName($name); if($robot){ $this->flash->success("id:".$robot->id. 'name:' .$name . "email:" . $robot->email); }else{ $this->flash->error("There were no robots found in our table with the name " . $name); }
//插入数据到数据库(save) $user = new Users(); //1 $user -> name = "xx"; $user -> email = "[email protected]"; if ($user->save() == false) { //if ($user->create() == false){ echo "Umh, We can't store robots right now: \n"; foreach ($user->getMessages() as $message) { echo $message, "\n"; } } else { echo "Great, a new robot was saved successfully!"; } //2 $user->save(array( "name"=>"leon", "email"=>"[email protected]" ));
$user = Users::findFirst(11); //删除数据 if ($user != false) { if ($user->delete() == false) { echo "Sorry, we can't delete the robot right now: \n"; foreach ($user->getMessages() as $message) { echo $message, "\n"; } } else { echo "The robot was deleted successfully!"; } } //带参数删除 foreach (Users::find("id='3'") as $user) { if ($user->delete() == false) { echo "Sorry, we can't delete the robot right now: \n"; foreach ($user->getMessages() as $message) { echo $message, "\n"; } } else { echo "The robot was deleted successfully!"; } } //全部删除(建议别乱用) foreach($user as $u){ $u->delete(); } //还有一个直接的 $user->delete();//和foreach一样
以下事件可定义自定义的业务规则,可以执行删除操作进行时:
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 |
<?php class Robots extends Phalcon\Mvc\Model { public function beforeDelete() { if ($this->status == 'A') { echo "The robot is active, it can't be deleted"; return false; } return true; } }
(可以在这里事件中添加业务逻辑)
Validation Failed Events 验证失败事件
Another type of events are available when the data validation process finds any inconsistency:
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 |
//更新相关记录
foreach ($user->getParts() as $part) { $part->stock = 100; $part->updated_at = time(); if ($part->update() == false) { foreach ($part->getMessages() as $message) { echo $message; } break; } } $user->getParts()->update(array( 'stock' => 100, 'updated_at' => time() )); //‘update’ also accepts an anonymous function to filter what records must be updated: $data = array( 'stock' => 100, 'updated_at' => time() ); //Update all the parts except these whose type is basic $user->getParts()->update($data, function($part) { if ($part->type == Part::TYPE_BASIC) { return false; } return true; });
//删除相关记录 foreach ($user->getParts() as $part) { if ($part->delete() == false) { foreach ($part->getMessages() as $message) { echo $message; } break; } } <?php $robots->getParts()->delete(); ‘delete’ also accepts an anonymous function to filter what records must be deleted:
支持的消息类型:
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 |
InvalidCreateAttempt | Produced when a record is attempted to be created but it already exists |
InvalidUpdateAttempt | Produced when a record is attempted to be updated but it doesn’t exist |
模型允许你去实现当执行insert/update/delete时被抛出的事件。一下是Phalcon\Mvc\Model支持的事件和它们执行的顺序:
Operation | Name | Can stop operation? | Explanation |
---|---|---|---|
Inserting/Updating | beforeValidation | YES | Is executed before the fields are validated for not nulls/empty strings or foreign keys |
Inserting | beforeValidationOnCreate | YES | Is executed before the fields are validated for not nulls/empty strings or foreign keys when an insertion operation is being made |
Updating | beforeValidationOnUpdate | YES | Is executed before the fields are validated for not nulls/empty strings 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/empty strings or foreign keys when an insertion operation is being made |
Updating | afterValidationOnUpdate | YES | Is executed after the fields are validated for not nulls/empty strings or foreign keys when an updating operation is being made |
Inserting/Updating | afterValidation | YES | Is executed after the fields are validated for not nulls/empty strings 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 |
设置多数据库:
可以属于相同数据库链接也可以属于私有的。Phalcon\Mvc\Model需要数据库链接时,它向容器获取db服务。所以可以重新这个服务的初始化:
<?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" )); }); //具体模型中 <?php class Robots extends \Phalcon\Mvc\Model { public function initialize() { $this->setConnectionService('dbPostgres'); } }
可以定义读写链接,在主从复制结构中非常有用:
class Robots extends \Phalcon\Mvc\Model { public function initialize() { $this->setReadConnectionService('dbSlave'); $this->setWriteConnectionService('dbMaster'); } } class Robots extends Phalcon\Mvc\Model { /** * Dynamically selects a shard * * @param array $intermediate * @param array $bindParams * @param array $bindTypes */ public function selectReadConnection($intermediate, $bindParams, $bindTypes) { //Check if there is a 'where' clause in the select if (isset($intermediate['where'])) { $conditions = $intermediate['where']; //Choose the possible shard according to the conditions if ($conditions['left']['name'] == 'id') { $id = $conditions['right']['value']; if ($id > 0 && $id < 10000) { return $this->getDI()->get('dbShard1'); } if ($id > 10000) { return $this->getDI()->get('dbShard2'); } } } //Use a default shard return $this->getDI()->get('dbShard0'); } }
一个向前的动作接受下列参数:控制器跳转 forward
Parameter | Triggered |
---|---|
controller | 一个有效的控制器的名字了。 |
action | 一个有效的模型的名字了。 |
params | 对于动作的参数的数组 |
namespace | 一个有效的命名空间名称,其中控制器部分 |
9、视图
$this->view->pick("控制器/模板");