Phalcon VS Spring 用法对照手册

时间:2022-05-03
本文章向大家介绍Phalcon VS Spring 用法对照手册,主要内容包括Phalcon VS Spring、1. Install、1.2. Spring、2. Project initialization、2.2. Spring、3. Controller、3.2. pathinfo、3.3. HTTP Get、3.4. HTTP Post、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Phalcon VS Spring

摘要

Phalcon VS Spring 用法对照表


目录

  • 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

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 PhalconMvcDispatcher;
use PhalconEventsManager as EventsManager;
use PhalconLogger;
try {


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

	$loader = new PhalconLoader();

	/**
	 * 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 PhalconDIFactoryDefault();

        $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 PhalconMvcUrl();
		$url->setBaseUri($config->application->baseUri);
		return $url;
	});

	/**
	 * Setting up the view component
	 */
	$di->set('view', function() use ($config) {
		$view = new PhalconMvcView();
		$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 PhalconDbAdapterPdoMysql(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 PhalconSessionAdapterFiles();
  		$session->start();
  		return $session;
  	});
/*
	$di->set('session', function() use ($config) {
		$session = new PhalconSessionAdapterRedis(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 = 'PhalconMvcModelMetadata\'.$config->models->metadata->adapter;
			return new $metadataAdapter();
		} else {
			return new PhalconMvcModelMetadataMemory();
		}
	});

	/**
	 * If the configuration specify the use of metadata adapter use it or use memory otherwise
	 */
	$di->set('modelsManager', function() {
		return new PhalconMvcModelManager();
	});


	/**
	 * Handle the request
	 */
	$application = new PhalconMvcApplication();
	$application->setDI($di);
	echo $application->handle()->getContent();

} catch (PhalconException $e) {
	echo $e->getMessage();
} catch (PDOException $e){
	echo $e->getMessage();
}			

2.2. Spring

WebContentWEB-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 PhalconMvcController
{


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

}