Phalcon VS Spring 用法对照表(一)

…衆ロ難τιáo~ 提交于 2019-12-06 06:43:31

Home | 简体中文 | 繁体中文 | 杂文 | Search | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | Email

Phalcon VS Spring

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

Mr. Neo Chen (陈景峯), netkiller, BG7NYT


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

<netkiller@msn.com>

版权声明

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

文档出处:
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

FYI https://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/

git clone --depth=1 git://github.com/phalcon/cphalcon.git
cd cphalcon/build
./install

cat > /srv/php/etc/conf.d/phalcon.ini <<EOF
extension=phalcon.so
EOF

1.2. Spring

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Spring</groupId>
	<artifactId>Spring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>4.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.1.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.3</version>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

2. Project initialization

2.1. Phalcon

<?php
use Phalcon\Mvc\Dispatcher;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Logger;
try {


	/**
	 * Read the configuration
	 */
	$config = include(__DIR__."/../app/config/config.php");

	$loader = new \Phalcon\Loader();

	/**
	 * We're a registering a set of directories taken from the configuration file
	 */
	$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();

	/**
	 * 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

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Spring</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>netkiller</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>netkiller</servlet-name>
        <url-pattern>/welcome.jsp</url-pattern>
        <url-pattern>/welcome.html</url-pattern>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

</web-app>

netkiller-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	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">

	<context:component-scan base-package="cn.netkiller.controller" />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

3. Controller

3.1. welcome

3.1.1. Phalcon

<?php

class IndexController extends ControllerBase
{

    public function indexAction()
    {

    }
    public function welcomeAction()
    {
    	$message = "Helloworld!!!";
		$this->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;

@Controller
public 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

<?php

class NewsController extends \Phalcon\Mvc\Controller
{


    public function listAction($category_id)
    {
		$this->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;

@Controller
public 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

<?php

class MemberController extends ControllerBase
{

    public function loginAction()
    {
		echo "email=" . $request->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;

@Controller
public 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;

@Controller
public 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

<?php

class MemberController extends ControllerBase
{

    public function loginAction()
    {
		echo "email=" . $request->getPost("email");
    }

}

3.4.2. Spring


4. View

4.1. Variable

4.1.1. Phalcon

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<?php echo ${message} ?>
</body>
</html>

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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	${message}
</body>
</html>

4.2. Array

4.2.1. Phalcon

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

	<?php foreach($books as $book) {?>
		<?php echo $book ?> <br>
	<?php } ?>

</body>
</html>

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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

	<c:forEach items="${books}" var="book">
		<c:out value="${book}"></c:out><br>
	</c:forEach>

</body>
</html>

4.3. Map or Hashmap

4.3.1. Phalcon

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

	<?php foreach($books as $key=>$value) {?>
		<?php echo $key ?> : <?php echo $value ?> <br>
	<?php } ?>

</body>
</html>

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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<c:forEach items="${books}" var="book">
		<c:out value="${book.key}"></c:out> : <c:out value="${book.value}"></c:out> <br>
	</c:forEach>
</body>
</html>

4.4. From

4.4.1. Phalcon

<?php

use Phalcon\Tag;

$this->tag->setDoctype(Tag::HTML401_STRICT);

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

<?php = $this->tag->endForm() ?>
</body>
</html>

4.4.2. Spring

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

<form:form method="POST" commandName="user">

	<form:input path="name" />
	<form:password path="password" />

    <form:radiobutton path="gender" value="M" label="M" />
    <form:radiobutton path="gender" value="F" label="F" />

    <form:select path="country">
	    <form:option value="0" label="Select" />
	    <form:options items="${countryList}" itemValue="countryId" itemLabel="countryName" />
    </form:select>

    <form:textarea path="aboutYou" />
    <form:checkboxes path="communityList" items="${communityList}" itemValue="key" itemLabel="value" />
    <form:checkbox path="mailingList" label="Would you like to join our mailinglist?" />

    <input type="submit" value="Register">

</form:form>

</body>
</html>

5. Model

5.1. Phalcon

模型定义

<?php

class User extends \Phalcon\Mvc\Model
{
	public function initialize()
	{

	}
}

在控制器重调用查询数据

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

5.2. MyBatis

Maven 增加mybatis与mysql依赖设置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>MyBatis</groupId>
	<artifactId>MyBatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.3.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.37</version>
		</dependency>
	</dependencies>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<!-- 配置数据库连接信息 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://192.168.6.1:3306/mybatis" />
				<property name="username" value="mybatis" />
				<property name="password" value="mybatis" />
			</dataSource>
		</environment>
	</environments>
	<mappers>

		<mapper resource="cn/netkiller/mapping/userMapping.xml" />
	</mappers>
</configuration>

cn/netkiller/mapping/userMapping.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.netkiller.mapping.UserMapping">
	<select id="getUser" parameterType="String" resultType="cn.netkiller.model.User">
		select * from user where id=#{id}
	</select>
</mapper>

数据类型映射

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

6.1. Redis

6.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');

6.1.2. Spring

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.6.1.RELEASE</version>
    </dependency>
</dependencies>

Configure RedisTemplate....

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

<!-- redis template definition -->
<bean id="redisTemplate" 
    class="org.springframework.data.redis.core.RedisTemplate" 
    p:connection-factory-ref="jedisConnFactory"/>

Testing

public class Example {

    // inject the actual template
    @Autowired
    private RedisTemplate<String, String> template;

    // inject the template as ListOperations
    // can also inject as Value, Set, ZSet, and HashOperations
    @Resource(name="redisTemplate")
    private ListOperations<String, String> listOps;

    public void addLink(String userId, URL url) {
        listOps.leftPush(userId, url.toExternalForm());
        // or use template directly
        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

  <dependencies>
    <!--
     | Provided dependencies
    -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
      <scope>provided</scope>
    </dependency>

    <!--
     | compile dependencies
    -->
	<dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.7.3</version>
      <scope>compile</scope>
	</dependency>
  </dependencies>




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

输出

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

)

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

8. Message Queue

8.1. Phalcon


8.2. Spring



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!