Phalcon VS Spring 用法对照表(一)

2016-07-12 10:27:35来源:oschina作者:neo-chen人点击

Home|简体中文|繁体中文|杂文|Search|ITEYE 博客|OSChina 博客|Facebook|Linkedin|Email
Phalcon VS Spring
http://www.netkiller.cn/journal/phalcon.spring.html
Mr.Neo Chen(陈景峯),netkiller, BG7NYT

中国广东省深圳市龙华新区民治街道溪山美地518131+8613113668890


版权声明


转载请与作者联系,转载时请务必标明文章原始出处和作者信息及本声明。






文档出处: http://netkiller.github.io http://netkiller.sourceforge.net

微信扫描二维码进入 Netkiller 微信订阅号

QQ群:128659835 请注明“读者”



2015-11-25


摘要


Phalcon VS Spring 用法对照表


我的系列文档


编程语言



Netkiller Architect 手札
Netkiller Developer 手札
Netkiller PHP 手札
Netkiller Python 手札
Netkiller Testing 手札
Netkiller Cryptography 手札


Netkiller Perl 手札
Netkiller Docbook 手札
Netkiller Project 手札
Netkiller Java 手札
Netkiller DevOps 手札

操作系统



Netkiller Linux 手札
Netkiller Debian 手札
Netkiller CentOS 手札
Netkiller FreeBSD 手札
Netkiller Shell 手札
Netkiller Security 手札


Netkiller Web 手札
Netkiller Monitoring 手札
Netkiller Storage 手札
Netkiller Mail 手札
Netkiller Multimedia 手札

数据库



Netkiller Database 手札
Netkiller PostgreSQL 手札
Netkiller MySQL 手札
Netkiller NoSQL 手札
Netkiller LDAP 手札

网络设备及其他



Netkiller Network 手札
Netkiller Cisco IOS 手札
Netkiller H3C 手札
Netkiller Amateur Radio 手札

您可以使用iBook阅读当前文档

目录

1. Install

1.1. Phalcon


1.2. Spring

2. Project initialization

2.1. Phalcon


2.2. Spring

3. Controller

3.4.1. Phalcon


3.4.2. Spring


3.3.1. Phalcon


3.3.2. Spring


3.2.1. Phalcon


3.2.2. Spring


3.1.1. Phalcon


3.1.2. Spring


3.1. welcome


3.2. pathinfo


3.3. HTTP Get


3.4. HTTP Post

4. View

4.4.1. Phalcon


4.4.2. Spring


4.3.1. Phalcon


4.3.2. Spring


4.2.1. Phalcon


4.2.2. Spring


4.1.1. Phalcon


4.1.2. Spring


4.1. Variable


4.2. Array


4.3. Map or Hashmap


4.4. From

5. Model

5.1. Phalcon


5.2. MyBatis

6. Cache

6.3.1.


6.3.2.


6.2.1. Phalcon


6.2.2. MyBatis


6.1.1. Phalcon


6.1.2. Spring


6.1. Redis


6.2. Model + Cache


6.3. Phalcon vs Ehcache

7. JSON Data

7.1. Phalcon


7.2. Spring

8. Message Queue

8.1. Phalcon


8.2. Spring


1.Install
1.1.Phalcon

FYIhttps://github.com/oscm/shell/blob/master/lang/php/pecl/phalcon.sh


You need to install with compiler, make tools.


#!/bin/sh
cd/usr/local/src/
gitclone--depth=1git://github.com/phalcon/cphalcon.git
cdcphalcon/build
./install
cat>/srv/php/etc/conf.d/phalcon.ini<extension=phalcon.so
EOF
1.2.Spring

You just only create a file as pom.xml, the maven will be fetch them.


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
Spring
Spring
0.0.1-SNAPSHOT
war


org.springframework
spring-context
4.1.1.RELEASE


org.springframework
spring-aop
4.1.1.RELEASE


org.springframework
spring-webmvc
4.1.1.RELEASE


org.springframework
spring-web
4.1.1.RELEASE


javax.servlet
jstl
1.2


commons-logging
commons-logging
1.1.3



src


maven-compiler-plugin
3.3

1.6
1.6



maven-war-plugin
2.6

WebContent
false





2.Project initialization
2.1.Phalcon
<?php
usePhalcon/Mvc/Dispatcher;
usePhalcon/Events/ManagerasEventsManager;
usePhalcon/Logger;
try{ /**
*Readtheconfiguration
*/
$config=include(__DIR__."/../app/config/config.php");
$loader=new/Phalcon/Loader();
/**
*We'rearegisteringasetofdirectoriestakenfromtheconfigurationfile
*/
$loader->registerDirs(
array(
$config->application->controllersDir,
$config->application->modelsDir,
$config->application->formsDir,
$config->application->imagesDir,
)
)->register();
$loader->registerNamespaces(array(
'Phalcon'=>__DIR__.'/../../Library/Phalcon/'
));
$loader->register();
/**
*TheFactoryDefaultDependencyInjectorautomaticallyregistertherightservicesprovidingafullstackframework
*/
$di=new/Phalcon/DI/FactoryDefault();
$di->set('dispatcher',function()use($di){
$eventsManager=newEventsManager;
$dispatcher=newDispatcher;
$dispatcher->setEventsManager($eventsManager);
return$dispatcher;
});
/**
*TheURLcomponentisusedtogenerateallkindofurlsintheapplication
*/
$di->set('url',function()use($config){
$url=new/Phalcon/Mvc/Url();
$url->setBaseUri($config->application->baseUri);
return$url;
});
/**
*Settinguptheviewcomponent
*/
$di->set('view',function()use($config){
$view=new/Phalcon/Mvc/View();
$view->setViewsDir($config->application->viewsDir);
return$view;
});
/**
*数据库加密key
*/
$di->set('config',function()use($config){
return$config;
}); /**
*Databaseconnectioniscreatedbasedintheparametersdefinedintheconfigurationfile
*/
$di->set('db',function()use($config){
returnnew/Phalcon/Db/Adapter/Pdo/Mysql(array(
"host"=>$config->database->host,
"username"=>$config->database->username,
"password"=>$config->database->password,
"dbname"=>$config->database->dbname
));
});
/**
*Startthesessionthefirsttimesomecomponentrequestthesessionservice
*/
$di->set('session',function(){
$session=new/Phalcon/Session/Adapter/Files();
$session->start();
return$session;
});
/*
$di->set('session',function()use($config){
$session=newPhalcon/Session/Adapter/Redis(array(
'path'=>sprintf("tcp://%s:%s?weight=1",$config->redis->host,$config->redis->port)
));
$session->start();
return$session;
});
*/
/**
*Iftheconfigurationspecifytheuseofmetadataadapteruseitorusememoryotherwise
*/
$di->set('modelsMetadata',function()use($config){
if(isset($config->models->metadata)){
$metadataAdapter='Phalcon/Mvc/Model/Metadata//'.$config->models->metadata->adapter;
returnnew$metadataAdapter();
}else{
returnnew/Phalcon/Mvc/Model/Metadata/Memory();
}
});
/**
*Iftheconfigurationspecifytheuseofmetadataadapteruseitorusememoryotherwise
*/
$di->set('modelsManager',function(){
returnnewPhalcon/Mvc/Model/Manager();
}); /**
*Handletherequest
*/
$application=new/Phalcon/Mvc/Application();
$application->setDI($di);
echo$application->handle()->getContent();
}catch(Phalcon/Exception$e){
echo$e->getMessage();
}catch(PDOException$e){
echo$e->getMessage();
}
2.2.Spring

WebContent/WEB-INF


<?xmlversion="1.0"encoding="UTF-8"?>

Spring

index.html
index.htm
index.jsp
default.html
default.htm
default.jsp


netkiller

org.springframework.web.servlet.DispatcherServlet

1


netkiller
/welcome.jsp
/welcome.html
*.html


netkiller-servlet.xml


xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

class="org.springframework.web.servlet.view.UrlBasedViewResolver">
value="org.springframework.web.servlet.view.JstlView"/>



3.Controller
3.1.welcome
3.1.1.Phalcon
<?php
classIndexControllerextendsControllerBase
{
publicfunctionindexAction()
{
}
publicfunctionwelcomeAction()
{
$message="Helloworld!!!";
$this->view->setVar('message',$message);
}
}
3.1.2.Spring
packagecn.netkiller.controller;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.servlet.ModelAndView;
@Controller
publicclassWelcome{
@RequestMapping("/welcome")
publicModelAndViewhelloWorld(){
Stringmessage="Helloworld!!!";
returnnewModelAndView("welcome","message",message);
}
}
3.2.pathinfo

http://www.netkiller.cn/news/list/100.html


http://www.netkiller.cn/news/detail/100/1000.html


3.2.1.Phalcon
<?php
classNewsControllerextends/Phalcon/Mvc/Controller
{publicfunctionlistAction($category_id)
{
$this->view->setVar('category_id',$category_id);
}
publicfunctiondetailAction($category_id,$article_id)
{
$this->view->setVar('category_id',$category_id);
$this->view->setVar('article_id',$article_id);
}
}
3.2.2.Spring
packagecn.netkiller.controller;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.ModelMap;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.servlet.ModelAndView;
@Controller
publicclassPathinfo{
@RequestMapping("/news/list/{category_id}")
publicModelAndViewurlTestId(@PathVariableStringcategory_id){
returnnewModelAndView("news/list","category_id",category_id);
}
@RequestMapping("/news/detail/{category_id}/{article_id}")
publicModelAndViewurlTestId(@PathVariableStringcategory_id,@PathVariableStringarticle_id){
ModelMapmodel=newModelMap();
model.addAttribute("category_id",category_id);
model.addAttribute("article_id",article_id);
returnnewModelAndView("news/detail",model);
}
}
3.3.HTTP Get

http://www.netkiller.cn/member/login?email=netkiller@msn.com


3.3.1.Phalcon
<?php
classMemberControllerextendsControllerBase
{
publicfunctionloginAction()
{
echo"email=".$request->get("email");
}
}
3.3.2.Spring
packagecn.netkiller.controller;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.servlet.ModelAndView;
@Controller
publicclassWelcome{
@RequestMapping("/member/login")
@ResponseBody
publicStringgetEmailWithRequestParam(@RequestParam("email")Stringemail){
return"email="+email;
}
}

如果参数很多写起来就非常辛苦


packagecn.netkiller.controller;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.servlet.ModelAndView;
@Controller
publicclassWelcome{
@RequestMapping("/member/login")
@ResponseBody
publicStringgetEmailWithRequestParam(
@RequestParam("email")Stringemail
@RequestParam("password")Stringpassword
...
...
@RequestParam("ext")Stringext
){
...
...
...
}
}
3.4.HTTP Post
3.4.1.Phalcon
<?php
classMemberControllerextendsControllerBase
{
publicfunctionloginAction()
{
echo"email=".$request->getPost("email");
}
}
3.4.2.Spring 4.View
4.1.Variable
4.1.1.Phalcon




Inserttitlehere


<?phpecho${message}?>


4.1.2.Spring
<%@pagelanguage="java"contentType="text/html;charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%>




Inserttitlehere


${message}


4.2.Array
4.2.1.Phalcon




Inserttitlehere


<?phpforeach($booksas$book){?>
<?phpecho$book?>
<?php}?>


4.2.2.Spring
<%@pagelanguage="java"contentType="text/html;charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%>




Inserttitlehere







4.3.Map or Hashmap
4.3.1.Phalcon




Inserttitlehere


<?phpforeach($booksas$key=>$value){?>
<?phpecho$key?>:<?phpecho$value?>
<?php}?>


4.3.2.Spring
<%@pagelanguage="java"contentType="text/html;charset=utf-8"
pageEncoding="utf-8"%>
<%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%>




Inserttitlehere



:



4.4.From
4.4.1.Phalcon
<?php
usePhalcon/Tag;
$this->tag->setDoctype(Tag::HTML401_STRICT);
?>


RegistrationPage


<?php=$this->tag->form("products/search")?>
<?php=$this->tag->textField("name")?>
<?phpecho$this->tag->passwordField(array("password","size"=>30))?>
<?phpecho$this->tag->select(array("status",array("A"=>"Active","I"=>"Inactive")));?>
<?phpecho$this->tag->textArea(array("aboutYou","","cols"=>"6","rows"=>20))?>
<?phpecho$this->tag->hiddenField(array("parent_id","value"=>"5"))?>
<?=$this->tag->submitButton("Register");?>
<?php=$this->tag->endForm()?>


4.4.2.Spring
<%@tagliburi="http://www.springframework.org/tags/form"prefix="form"%>


RegistrationPage


















5.Model
5.1.Phalcon

模型定义


<?php
classUserextends/Phalcon/Mvc/Model
{
publicfunctioninitialize()
{
}
}

在控制器重调用查询数据


<?php
$user=User::find();
print_r($user);
5.2.MyBatis

Maven 增加mybatis与mysql依赖设置


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
MyBatis
MyBatis
0.0.1-SNAPSHOT


junit
junit
3.8.1
test


org.mybatis
mybatis
3.3.0


mysql
mysql-connector-java
5.1.37



src


maven-compiler-plugin
3.3

1.8
1.8





mybatis.xml


<?xmlversion="1.0"encoding="UTF-8"?>


















cn/netkiller/mapping/userMapping.xml


<?xmlversion="1.0"encoding="UTF-8"?>



select*fromuserwhereid=#{id}


数据类型映射


packagecn.netkiller.model;
publicclassUser{
privateStringid;
privateStringname;
privateintage;
publicStringgetId(){
returnid;
}
publicvoidsetId(Stringid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
@Override
publicStringtoString(){
return"User[id="+id+",name="+name+",age="+age+"]";
}
}

测试程序


packagecn.netkiller.test;
importjava.io.InputStream;
importorg.apache.ibatis.session.SqlSession;
importorg.apache.ibatis.session.SqlSessionFactory;
importorg.apache.ibatis.session.SqlSessionFactoryBuilder;
importcn.netkiller.model.*;
publicclassTest{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
Stringresource="mybatis.xml";
InputStreamis=Tests.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactorysessionFactory=newSqlSessionFactoryBuilder().build(is);
SqlSessionsession=sessionFactory.openSession();
Stringstatement="cn.netkiller.mapping.UserMapping.getUser";//映射sql的标识字符串
Useruser=session.selectOne(statement,"2");
System.out.println(user.toString());
}
}
6.Cache
6.1.Redis
6.1.1.Phalcon
//Cachearbitrarydata
$this->cache->save('my-key',array(1,2,3,4,5));
//Getdata
$data=$this->cache->get('my-key');
6.1.2.Spring

pom.xml




org.springframework.data
spring-data-redis
1.6.1.RELEASE


Configure RedisTemplate....


class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:use-pool="true"/>

class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnFactory"/>

Testing


publicclassExample{
//injecttheactualtemplate
@Autowired
privateRedisTemplatetemplate;
//injectthetemplateasListOperations
//canalsoinjectasValue,Set,ZSet,andHashOperations
@Resource(name="redisTemplate")
privateListOperationslistOps;
publicvoidaddLink(StringuserId,URLurl){
listOps.leftPush(userId,url.toExternalForm());
//orusetemplatedirectly
redisTemplate.boundListOps(userId).leftPush(url.toExternalForm());
}
}
6.2.Model + Cache
6.2.1.Phalcon
$articles=Article::find(array(
"cache"=>array("service"=>'redis',"key"=>$key,"lifetime"=>60)
));
6.2.2.MyBatis

MyBatis Redis Cache adapter http://mybatis.github.io/redis-cache


pom.xml





org.mybatis
mybatis
3.3.0
provided



redis.clients
jedis
2.7.3
compile


6.3.Phalcon vs Ehcache
6.3.1. 6.3.2. 7.JSON Data
7.1.Phalcon

Encode


<?php
$json=array(
'contact'=>array(
'name' =>'Neo',
'website' =>'http://www.netkiller.cn',
'nickname' =>'netkiller'
)
);
print(json_encode($json));

Output


{"contact":{"name":"Neo","website":"http:////www.netkiller.cn","nickname":"netkiller"}}

Decode


<?php
$string='{"contact":{"name":"Neo","website":"http:////www.netkiller.cn","nickname":"netkiller"}}';
print_r(json_decode($string));

输出


stdClassObject
(
[contact]=>stdClassObject
(
[name]=>Neo
[website]=>http://www.netkiller.cn
[nickname]=>netkiller
)
)
7.2.Spring

JSON 编码


packagenetkiller.json;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjavax.json.*;
publicfinalclassWriter{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
JsonObjectBuilderjsonBuilder=Json.createObjectBuilder();
JsonObjectBuilderaddressBuilder=Json.createObjectBuilder();
JsonArrayBuilderphoneNumBuilder=Json.createArrayBuilder();
phoneNumBuilder.add("12355566688").add("0755-2222-3333");
addressBuilder.add("street","Longhua").add("city","Shenzhen").add("zipcode",518000);
jsonBuilder.add("nickname","netkiller").add("name","Neo").add("department","IT").add("role","Admin");
jsonBuilder.add("phone",phoneNumBuilder);
jsonBuilder.add("address",addressBuilder);
JsonObjectjsonObject=jsonBuilder.build();
System.out.println(jsonObject);
try{
//writetofile
Filefile=newFile("json.txt");
if(!file.exists()){
file.createNewFile();
}
OutputStreamos=null;
os=newFileOutputStream(file);
JsonWriterjsonWriter=Json.createWriter(os);
jsonWriter.writeObject(jsonObject);
jsonWriter.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}

运行后输出
{"nickname":"netkiller","name":"Neo","department":"IT","role":"Admin","phone":["12355566688","0755-2222-3333"],"address":{"street":"Longhua","city":"Shenzhen","zipcode":"518000"}}

JSON 解码


packagenetkiller.json;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjavax.json.Json;
importjavax.json.JsonArray;
importjavax.json.JsonObject;
importjavax.json.JsonReader;
importjavax.json.JsonValue;
publicfinalclassReader{
publicstaticfinalStringJSON_FILE="json.txt";
publicstaticvoidmain(String[]args)throwsIOException{
InputStreamfis=newFileInputStream(JSON_FILE);
//createJsonReaderobject
JsonReaderjsonReader=Json.createReader(fis);
//getJsonObjectfromJsonReader
JsonObjectjsonObject=jsonReader.readObject();
//wecancloseIOresourceandJsonReadernow
jsonReader.close();
fis.close();
System.out.printf("nickname:%s/n",jsonObject.getString("nickname"));
System.out.printf("name:%s/n",jsonObject.getString("name"));
System.out.printf("department:%s/n",jsonObject.getString("department"));
System.out.printf("role:%s/n",jsonObject.getString("role"));
JsonArrayjsonArray=jsonObject.getJsonArray("phone");
//long[]numbers=newlong[jsonArray.size()];
intindex=0;
for(JsonValuevalue:jsonArray){
//numbers[index++]=Long.parseLong(value.toString());
System.out.printf("phone[%d]:%s/n",index++,value.toString());
}
//readinginnerobjectfromjsonobject
JsonObjectinnerJsonObject=jsonObject.getJsonObject("address");
System.out.printf("address:%s,%s,%d/n",innerJsonObject.getString("street"),innerJsonObject.getString("city"),innerJsonObject.getInt("zipcode"));
}
}

运行结果
nickname:netkiller
name:Neo
department:IT
role:Admin
phone[0]:+8612355566688
phone[1]:0755-2222-3333
address:Longhua,Shenzhen,518000
8.Message Queue
8.1.Phalcon 8.2.Spring

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台