博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Phalcon vs Spring 用法对照表(持续更新)
阅读量:6579 次
发布时间:2019-06-24

本文共 21476 字,大约阅读时间需要 71 分钟。

Phalcon vs Spring

http://www.netkiller.cn/journal/phalcon.spring.html

MrNeo Chen (陈景峯)netkiller, BG7NYT

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

版权声明

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

文档出处:

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

群:128659835 请注明“读者”

 

2015-11-25

摘要

Phalcon VS  用法对照表

我的系列文档

编程语言

 

操作系统

 

 

网络设备及其他

   

您可以使用阅读当前文档


目录

1. Install

1.1. Phalcon

FYI 

You need to install with compiler, make tools.

#!/bin/shcd /usr/local/src/git clone --depth=1 git://github.com/phalcon/cphalcon.gitcd cphalcon/build./installcat > /srv/php/etc/conf.d/phalcon.ini <

1.2. Spring

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

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

registerDirs( array( $config->application->controllersDir, $config->application->modelsDir, $config->application->formsDir, $config->application->imagesDir, ) )->register(); $loader->registerNamespaces(array( 'Phalcon' => __DIR__.'/../../Library/Phalcon/' )); $loader->register(); /** * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework */ $di = new \Phalcon\DI\FactoryDefault(); $di->set('dispatcher', function() use ($di) { $eventsManager = new EventsManager; $dispatcher = new Dispatcher; $dispatcher->setEventsManager($eventsManager); return $dispatcher; }); /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function() use ($config) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($config->application->baseUri); return $url; }); /** * Setting up the view component */ $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; }); /** * 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->dbname )); }); /** * Start the session the first time some component request the session service */ $di->set('session', function() { $session = new \Phalcon\Session\Adapter\Files(); $session->start(); return $session; });/* $di->set('session', function() use ($config) { $session = new Phalcon\Session\Adapter\Redis(array( 'path' => sprintf("tcp://%s:%s?weight=1",$config->redis->host, $config->redis->port) )); $session->start(); return $session; });*/ /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */ $di->set('modelsMetadata', function() use ($config) { if (isset($config->models->metadata)) { $metadataAdapter = 'Phalcon\Mvc\Model\Metadata\\'.$config->models->metadata->adapter; return new $metadataAdapter(); } else { return new \Phalcon\Mvc\Model\Metadata\Memory(); } }); /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */ $di->set('modelsManager', function() { return new Phalcon\Mvc\Model\Manager(); }); /** * Handle the request */ $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

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

 

3. Controller

3.1. welcome

3.1.1. Phalcon

view->setVar('message',$message); }}

3.1.2. Spring

package cn.netkiller.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class Welcome {	@RequestMapping("/welcome")	public ModelAndView helloWorld() {		String message = "Helloworld!!!";		return new ModelAndView("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

view->setVar('category_id',$category_id); } public function detailAction($category_id, $article_id) { $this->view->setVar('category_id',$category_id); $this->view->setVar('article_id',$article_id); }}

3.2.2. Spring

package cn.netkiller.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class Pathinfo {	@RequestMapping("/news/list/{category_id}")	public ModelAndView urlTestId(@PathVariable String category_id) {		return new ModelAndView("news/list", "category_id", category_id);	}	@RequestMapping("/news/detail/{category_id}/{article_id}")	public ModelAndView urlTestId(@PathVariable String category_id, @PathVariable String article_id) {		ModelMap model = new ModelMap();		model.addAttribute("category_id", category_id);		model.addAttribute("article_id", article_id);		return new ModelAndView("news/detail", model);	}}

3.3. HTTP Get

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

3.3.1. Phalcon

get("email"); }}

3.3.2. Spring

package cn.netkiller.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class Welcome {	@RequestMapping("/member/login")	@ResponseBody	public String getEmailWithRequestParam(@RequestParam("email") String email) {	    return "email=" + email;	}}

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

package cn.netkiller.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class Welcome {	@RequestMapping("/member/login")	@ResponseBody	public String getEmailWithRequestParam(		@RequestParam("email") String email		@RequestParam("password") String password		...		...		@RequestParam("ext") String ext	) {	    ...	    ...	    ...	}}

3.4. HTTP Post

3.4.1. Phalcon

getPost("email"); echo "password=" . $request->getPost("password"); echo "phone=" . $request->getPost("phone"); }}

3.4.2. Spring

package cn.netkiller.controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class Member {	@RequestMapping("/http/form")	public ModelAndView createCustomer(){		ModelMap model = new ModelMap();		model.addAttribute("email", "netkiller@msn.com");		model.addAttribute("phone", "13113668890");			    return new ModelAndView("http/form", model);	}			@RequestMapping(value= "/http/post", method = RequestMethod.POST)	public ModelAndView saveCustomer(HttpServletRequest request, 	        @RequestParam(value="Email", required=false) String email, 	        @RequestParam(value="Password", required=false) String password, 	        @RequestParam(value="Phone", required=false) String phone){		ModelMap model = new ModelMap();		model.addAttribute("email", email);		model.addAttribute("password", password);		model.addAttribute("phone", phone);			    return new ModelAndView("http/post", model);	}	}

4. View

4.1. Variable

4.1.1. Phalcon

Insert title here

4.1.2. Spring

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"	pageEncoding="ISO-8859-1"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Insert title here ${message}

4.2. Array

4.2.1. Phalcon

Insert title here

4.2.2. Spring

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"	pageEncoding="ISO-8859-1"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Insert title here

4.3. Map or Hashmap

4.3.1. Phalcon

Insert title here
$value) {?>
:

4.3.2. Spring

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Insert title here
:

4.4. From

4.4.1. Phalcon

tag->setDoctype(Tag::HTML401_STRICT);?>Registration Page
tag->form("products/search") ?>
tag->textField("name") ?>
tag->passwordField(array("password", "size" => 30)) ?>
tag->select(array("status", array("A" => "Active","I" => "Inactive")));?>
tag->textArea(array("aboutYou","","cols" => "6","rows" => 20)) ?>
tag->hiddenField(array("parent_id","value"=> "5")) ?>
tag->submitButton("Register"); ?>
tag->endForm() ?>

4.4.2. Spring

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>Registration Page

5. Model

5.1. Phalcon

模型定义

在控制器重调用查询数据

5.2. MyBatis

Maven 增加mybatis与依赖设置

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

cn/netkiller/mapping/userMapping.xml

数据类型映射

package cn.netkiller.model;public class User {	private String id;	private String name;	private int age;	public String getId() {		return id;	}	public void setId(String id) {		this.id = id;	}	public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public int getAge() {		return age;	}	public void setAge(int age) {		this.age = age;	}	@Override	public String toString() {		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";	}}

测试程序

package cn.netkiller.test;import java.io.InputStream;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import cn.netkiller.model.*;public class Test {	public static void main(String[] args) {		// TODO Auto-generated method stub		String resource = "mybatis.xml";		InputStream is = Tests.class.getClassLoader().getResourceAsStream(resource);		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);		SqlSession session = sessionFactory.openSession();		String statement = "cn.netkiller.mapping.UserMapping.getUser";// 映射sql的标识字符串		User user = session.selectOne(statement, "2");		System.out.println(user.toString());	}}

6. Session

6.1. Phalcon

session->set("username", "netkiller"); } public function getAction() { // Check if the variable is defined if ($this->session->has("username")) { // Retrieve its value echo $this->session->get("username"); } } public function removeAction() { // Remove a session variable $this->session->remove("username"); } public function destroyAction() { // Destroy the whole session $this->session->destroy(); } }

传统方式

$_SESSION['username'] = "netkiller";unset($_SESSION['username']);

6.2. Spring

org.springframework.session
spring-session
1.0.2.RELEASE
package cn.netkiller.controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.view.RedirectView;import cn.netkiller.*;@Controllerpublic class Http {	@RequestMapping("/session")	@ResponseBody	public String home(HttpServletRequest request) {		return "" + request.getSession().getCreationTime();	}	@RequestMapping("/session/set")	@ResponseBody	public String setSession(HttpSession session) {		String username = "netkiller";		session.setAttribute("username", username);		return username;	}	@RequestMapping("/session/get")	@ResponseBody	public String getSession(HttpSession session) {		String username = (String) session.getAttribute("username");		return username;	}		@RequestMapping("/session/remove")	@ResponseBody	public String removeSession(HttpSession session) {		session.removeAttribute("username");		String username = (String) session.getAttribute("username");		return username;	}		@RequestMapping("/session/invalidate")	@ResponseBody	public String invalidateSession(HttpSession session) {		session.invalidate();		return "invalidate";	}}

Servlet 传统方式

@RequestMapping("/session/Servlet")	@ResponseBody	public String servletSession(HttpServletRequest request) {		String username = "neo";		request.getSession().setAttribute("username", username);		return username;	}

7. Cache

7.1. Redis

7.1.1. Phalcon

//Cache arbitrary data $this->cache->save('my-key', array(1, 2, 3, 4, 5)); //Get data $data = $this->cache->get('my-key');

7.1.2. Spring

pom.xml

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

Configure RedisTemplate....

Testing

public class Example {    // inject the actual template    @Autowired    private RedisTemplate
template; // inject the template as ListOperations // can also inject as Value, Set, ZSet, and HashOperations @Resource(name="redisTemplate") private ListOperations
listOps; public void addLink(String userId, URL url) { listOps.leftPush(userId, url.toExternalForm()); // or use template directly redisTemplate.boundListOps(userId).leftPush(url.toExternalForm()); }}

7.2. Model + Cache

7.2.1. Phalcon

$articles = Article::find(array(   			"cache" => array("service"=> 'redis', "key" => $key, "lifetime" => 60)   	));

7.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
 
 
 
 

7.3. Phalcon vs Ehcache

7.3.1. 

 

7.3.2. 

 

8. JSON Data

8.1. Phalcon

Encode

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

输出

stdClass Object(    [contact] => stdClass Object        (            [name] => Neo            [website] => http://www.netkiller.cn            [nickname] => netkiller        ))

8.2. Spring

JSON 编码

package netkiller.json;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import javax.json.*;public final class Writer {	public static void main(String[] args) {		// TODO Auto-generated method stub		JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();		JsonObjectBuilder addressBuilder = Json.createObjectBuilder();		JsonArrayBuilder phoneNumBuilder = 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);		JsonObject jsonObject = jsonBuilder.build();		System.out.println(jsonObject);		try {			// write to file			File file = new File("json.txt");			if (!file.exists()) {				file.createNewFile();			}			OutputStream os = null;			os = new FileOutputStream(file);			JsonWriter jsonWriter = Json.createWriter(os);			jsonWriter.writeObject(jsonObject);			jsonWriter.close();		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}	}}		运行后输出{"nickname":"netkiller","name":"Neo","department":"IT","role":"Admin","phone":["12355566688","0755-2222-3333"],"address":{"street":"Longhua","city":"Shenzhen","zipcode":"518000"}}

JSON 解码

package netkiller.json;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream; import javax.json.Json;import javax.json.JsonArray;import javax.json.JsonObject;import javax.json.JsonReader;import javax.json.JsonValue; public final class Reader {     public static final String JSON_FILE="json.txt";         public static void main(String[] args) throws IOException {        InputStream fis = new FileInputStream(JSON_FILE);        //create JsonReader object        JsonReader jsonReader = Json.createReader(fis);        //get JsonObject from JsonReader        JsonObject jsonObject = jsonReader.readObject();                 //we can close IO resource and JsonReader now        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"));        JsonArray jsonArray = jsonObject.getJsonArray("phone");                //long[] numbers = new long[jsonArray.size()];        int index = 0;        for(JsonValue value : jsonArray){            //numbers[index++] = Long.parseLong(value.toString());        	System.out.printf("phone[%d]: %s \n", index++, value.toString());        }        //reading inner object from json object        JsonObject innerJsonObject = 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

9. Message Queue

9.1. Phalcon

 

9.2. Spring

你可能感兴趣的文章
Quartz在Spring中动态设置cronExpression (spring设置动态定时任务)
查看>>
[翻译] hibernate映射继承关系(一):一张表对应一整棵类继承树
查看>>
NGUI官方示例教程 UIAnchor
查看>>
Understanding Docker
查看>>
Eclipse(Alt+/)没有代码自动提示功能
查看>>
云计算趋势:海量数据将发挥核心作用
查看>>
五步教你玩转Google Chrome浏览器
查看>>
SQL server 警报类型
查看>>
我的友情链接
查看>>
低秩矩阵的应用
查看>>
关于KickStart分区只使用特定硬盘分区
查看>>
LVS的10个调度算法
查看>>
select
查看>>
android binder机制
查看>>
setTimeout()相关知识
查看>>
我的友情链接
查看>>
linux下shell
查看>>
oracle的环境配置-监听服务和访问连接原理
查看>>
button标签在浏览器之间的小差别
查看>>
spring jdbc 多数据源 同时各自操作表
查看>>