On the REST

A, Web Services

     Web Services is a component-based software platform, service-oriented Internet applications. Web Services framework of core technologies, including SOAP, WSDL and UDDI, which are expressed in the form of standard XML documents.

   SOAP ( "Simple Object Access Protocol" acronym) is the Web Services communication protocol. SOAP is a simple, lightweight XML-based mechanism for structured data exchange between the network application. SOAP consists of three parts: a description of the message content envelope frame definition, data type instance encoding rules represent a set of application-defined, and agreed to represent remote procedure calls and responses.

  1. The format for the transmission of information in XML. This can enable Web Services on any platform, be implemented in any language.

  2. The format of the remote object method call. It specifies the method name and parameter types are called objects, and how to call the representation and so on.

  3. The mapping between the parameter type and XML format. This is because the method is called sometimes need to pass a complex parameters, for example, a Person object. How to represent an object parameter with XML, SOAP range is defined.

   WEB Service Description Language WSDL representation. WSDL file is an XML document, used to illustrate a set of SOAP messages and how to exchange these messages. When implementing a certain service time (such as: the stock inquiry service), in order to allow another program called, I must tell you that the service interface. For example: the name of the service, where the service machine name, listening port number, transmission type, number and order parameters, and return type of the result and the like. So that other applications can invoke the service. WSDL agreement that sets out standards for Web Services described.

  UDDI ( "Universal Description, Discovery, and Integration" abbreviation) provides a method to publish and find service descriptions. UDDI data entities provide support for the definition of business and service information. WSDL service description information defined in a UDDI registry information to add.

       Web Services works are as follows:

  1. Web Services service providers through the WSDL description of services provided, and to inform the description of Web Services registration server .

  2. Registration server according to WSDL description of, and posted on the Internet in accordance with the agreement UDDI directory service update.

  3. users give the registered server before using Web Services request, obtain a Web Services provider's address and service interface information.

  4. SOAP and Web Services protocol provider to establish a connection, for communication.

二、REST(Representational State Transfer) Web Services

      Usually we talk about Web Services is the first SOAP message exchange ideas on a variety of transport protocols. In fact, SOAP RPC was first for a solution, Simple Object Access Protocol, is very lightweight, but with a wide range of applications as SOAP Web Services, continue to add additional content, so that now developers think SOAP heavy use threshold high. There will be performance issues in large concurrent case, it is not popular on the Internet, and therefore not suitable for use Web 2.0 site service, currently a large number of Web 2.0 sites use another solution --REST.

  SOAP as a replacement mode, REST (is " Representational State Transfer " acronym) is a lightweight Web Services architectural style, its implementation and operation significantly more concise than the SOAP and XML-RPC, HTTP protocol completely by implemented, can also be used to improve the cache cache SOAP protocol is superior in response speed, performance, efficiency and ease of use.

    What is 1. RESTful Web Services

     REST is a term used by Dr. Roy Thomas Fielding presented in his paper "Architectural Styles and the Design of Network -based Software Architectures" in. REST itself just as a distributed hypermedia system design of an architectural style, instead of the standard. In a RESTful system, server resource utilization URI exposure, the client uses four Http predicates to access resources. Since the client receives a resource, they were placed in a certain state. When they visit a new resource, usually click on the next connection, they changed, or is in transit between their state. In order to work, REST assume that resources are able to use the universal standard syntax to represent.

Large traditional Web applications are B / S structure, which includes a number of the following specification.

  1. Client - Server : This specification proposes to improve the portability of user interfaces across multiple platforms, and by simplifying the server component, to improve the scalability of the system. The most critical is that by separating the user interface and data storage these two concerns, so that different user terminals to enjoy the same data as possible.

  2. statelessness : stateless in the client - server based on the constraints added yet another layer specification. It requires a communication to be stateless in nature, i.e. each request from the client to the server must be understood that contain all the information necessary for the request. This specification improves system visibility (stateless so that the client and server do not have to save the details of the other side, the server only needs to deal with the current request, without having to know all the history of the request), reliability (stateless reduce the server the amount of partial tasks to recover from the error), scalability (stateless server makes it easy to release resources, because the server does not have to request the plurality of saved state). Meanwhile, this specification is obvious drawbacks too, since the state of the data can not be stored in a shared context on the server, thus increasing the transmission request in a series of duplicate data overhead, severely reduces the efficiency.

  3. Cache : To improve the inefficiencies caused by stateless network, we add cache constraints. Cache constraint allows implicit or explicitly marked data in a response, thus imparting a functional response client data cache, so that a later request can be cached shared data, eliminating some or all of the part of the interaction, increased efficiency of the network. But for the client cache information, while also increasing the inconsistent client and server data possible, thereby reducing reliability.

  B / S structure of the advantages is that it is very easy to deploy, but it is not very satisfactory user experience. To improve this situation, we have introduced a REST!

  REST in the original architecture adds three new specifications: a unified interface, hierarchical systems and on-demand code.

  1. unified interface : the core features of the REST architectural style that emphasized a unified interface between components , which is reflected in the REST world where all things are on the network is abstracted as resources, REST is through a common interface to link resources to operate. The benefits of this design is to ensure that the service provided by the system are decoupled, greatly simplifying the system, thus improving the system's interactivity and reusability; and REST is optimized for the common case of the Web, so that the interface is REST hypermedia is designed to efficiently transfer large data size, which also led to other REST interface architecture is not optimal.

  2. tiered system : a hierarchical system of rules added to improve the independence between the various levels , setting the boundaries for the complexity of the overall system, by encapsulating the legacy of service, the new server from the effects of legacy clients, this also increases the scalability of the system.

  3. code on demand : REST allows to extend the functionality of the client . For example, by downloading and executing code in the form of a script or applet to extend the client capabilities. But at the same time improve system scalability, but also reduces visibility. So it's just an optional REST constraints.

     REST describes a design of Web applications architectural style, it is a set of architectural principles and constraints to meet these constraints and the application of the principles or design is RESTful style. And in line with RESTful style of Web Services, it is what we call RESTful Web Services.

     2. REST principles are as follows:

     REST architecture is designed for Web applications, and its purpose is to reduce development complexity, increase system scalability .

     REST resources not referring to data, but the data and forms of combination , such as "10 members of the latest visit" and "10 most active members" may have overlapping or identical to the data, and because they different forms, it is classified as different resources, which is why the full name of REST is Representational State Transfer of reason. Resource identifier is URI (Uniform Resource Identifier), whether it is pictures, Word or video file, or even just a virtual service, but also whether you are xml format, txt file format or other file formats, all uniquely resources by URI identity.

    REST is based on HTTP protocol , any operational behavior of resources are achieved through the HTTP protocol. Most previous Web development are used in the HTTP protocol GET and POST methods, other methods are rarely used, because this is actually one-sided understanding of understanding of the cause of the HTTP protocol. HTTP protocol network protocol software is not just a simple delivery of data, but a rich connotation. It can not only uniquely positioned to Internet resources, but also tells us how to operate the resource. HTTP put operation on a resource limited to less than four methods: GET, POST, PUT and DELETE, which is to realize the resource CRUD operations. Since the resource URI and is one to one, when performing these operations URI is not changed, this and previous Web development is quite different. Precisely because of this, greatly simplifies Web development, but also makes URI structure can be designed to reflect a more intuitive resources, this URI URI RESTful design is called, which introduces a new developers way of thinking: the URL to design the system architecture. Of course, this design approach for some specific cases is not applicable, which means that not all of RESTful URI can.

   REST reason can improve system scalability, because it requires that all operations are stateless. Since there is no context (Context) constraints, distributed and clustered to do when even simpler, you can also make the system more efficient use of the buffer pool (Pool), and since the server does not need to record a series of visits the client, also reduce the performance overhead on the server side.

    REST proposed the following design criteria

  • Resource specified by the URI:    In Web applications, all things should have a unique ID, ID represents the unifying concept is: URI. URI constitute a global namespace, use the URI to identify your key resources it means that they get a unique, global ID.
  • The method of HTTP using explicit:    the REST require developers to explicitly using HTTP methods, and consistent with the protocols defined manner. This basic REST design principles established to create, read, update, and delete one mapping between the (create, read, update, and delete, CRUD) operations and HTTP methods. According to this map:
    • To create a resource on the server, you should use the POST method.
    • To retrieve a resource, you should use the GET method.
    • To change or update the resource status, you should use the PUT method.
    • To delete a resource, use DELETE method.

           CRUD principles: the need for resources only four acts: Create (create), Read (read), Update (update) and Delete (delete) can complete its operation and processing

          In addition to abstract operation based CRUD. All interfaces are designed for resources to design, it is very similar to our process-oriented and object-oriented design difference, but now the operating entity on the network as a resource to look at, but also reflects the design URI for locating design resources

  • Multiple representations of resources:  resources multiple representations for different needs. Here's multiple representations, including XML, JSON, HTML and so on. That server needs to provide more resources to the external representation formats for different clients. Such as a mobile application may use XML or JSON communication and server-side, and the browser is able to understand HTML.
  • Stateless:    request to the server should be stateless, complete and independent request does not require the server to retrieve any type of application processing request context or state. Stateless constraints prevent changes in the server to the client is not visible, because two successive requests, the client does not rely on the same server. A client receives from a server on a document containing the link when it needs to do some processing, this server dawdle off, it may be hard to be broken for remedial work, probably you need to upgrade the software to restart - - If the client access server receives a link from this, it is not aware of the background to the server has changed.

  REST is not really what the agreement is not a standard, but the interpretation made Http protocol is designed, in the Http protocol is widely used today, it is more and more as a transport protocol, instead of the original designers application protocol to consider. Http SOAP message protocol is to complete as a message bearer, that for various parameters (e.g., coding, error code, etc.) are disregarded Http protocol.

  To give an example, HTTP GET requests in the request URI query string includes a set of parameters that define the server used to find a set of matching resources search criteria. But in many cases, not elegant Web API using HTTP GET to trigger transactional operations on the server - for example, to add records to the database. Such as:

  GET /adduser?name=John HTTP/1.1

   It's not a very good design, because the Web method above supports a state change operation through HTTP GET. Web servers are designed to query resources by retrieving the URI matches the request, and returns in the response or a representation of these resources, so that in response to an HTTP GET request, rather than adding records to the database. GET used in this way is inconsistent.

     REST is not just a new framework, it brings a new way of thinking is the Web development process : to design the system architecture through a URL. In REST, all of the URL corresponds to the resource, as long as the URL of the design is good, then the system structure of their presentation is good. This point and TDD (Test Driven Development) is very similar, it is through the test cases to design the system interface, each test case have expressed a range of user needs. Developers do not need to start writing function, but just need to be achieved by the function can be manifested in the form of test cases. This and REST design system by way of URL structure is similar, we just need to design a reasonable URL on demand, these URL not necessarily linked to a specific page or completion of some acts, as long as they are able to visually show users of the system interface. According to the URL, we can easily design the system architecture. Conceptually REST architecture point of view, all resources can be abstracted into everything can be specified as a URL, and developers need to do the job is how can a user needs to abstract resources, and how to abstract accurate . Because of the more precise abstract resources, the application of REST for the better, and this tradition MVC development model based on the idea of very large differences in Action. Good design URL, not only for developers can be more clear understanding of the system structure, also convenient for the user to remember and identify resources, because the URL is simple and meaningful enough. According to the previous design mode, many are behind a pile of URL parameters for the user is also very convenient.  

       Since REST so easy to use, it is not all Web applications can take such a structure? the answer is negative. We know that until now, MVC (Model-View-Controller ) model is still the most common Web development patterns, the vast majority of companies and developers have adopted this framework for developing Web applications and stay in their way of thinking this. The MVC pattern is composed of data, view and controller, and to change the Model View by the event (Event) triggered Controller. Plus added Webwork, Struts and other open source frameworks, MVC development model is already quite mature, the idea is simply to drive based Action. From a developer point of view, hastily accept a new architecture carries risks, which are too many uncertainties, and REST new way of thinking is all the user needs to abstract resources, it is relatively difficult to do in the actual development to, because not all user needs can be abstracted as resources , so that is not the structure of the entire system can be represented by the REST. So in development, we need to make a choice based on REST and MVC in more than two points. We believe that the better approach is to mix REST and MVC , because for the vast majority of Web application development, developers need only take on REST development model is easier to be able to abstract resource user needs, while taking MVC development for other needs It can be. It should be mentioned that ROR (Ruby on Rails) framework, which is based on the Ruby language increasingly popular Web development framework that greatly improves the speed of Web development. More importantly, ROR (since version 1.2) was the first to introduce REST framework as the core idea of the Web development framework that provides the best support for REST, Web development framework is the most successful application of REST . In fact, ROR is the realization of REST REST and MVC mix, ROR developers using the framework, you can build faster and better Web applications.

Three, RESTful Web Services and SOAP-based Web Services Comparison

      基于SOAP的Web Services也是解决异构系统间通信问题的常用方案,那么,RESTful Web Services相对于基于SOAP 的Web Services,有什么优势呢?或者说,我们为什么要开始学习RESTful Web Services,使用已经流行很久的基于SOAP的Web Services不就好了么?

  • RESTful Web Services接口更易于使用

        RESTful Web Services使用标准的 HTTP 方法 (GET/PUT/POST/DELETE) 来抽象所有 Web 系统的服务能力,而不同的是,SOAP 应用都通过定义自己个性化的接口方法来抽象 Web 服务。相对来说,RESTful Web Services接口更简单。

        RESTful Web Services使用标准的 HTTP 方法的优势,从大的方面来讲:标准化的 HTTP 操作方法,结合其他的标准化技术,如 URI,HTML,XML 等,将会极大提高系统与系统之间整合的互操作能力。尤其在 Web 应用领域,RESTful Web Services所表达的这种抽象能力更加贴近 Web 本身的工作方式,也更加自然。

  • 无状态性

      HTTP 协议从本质上说是一种无状态的协议,客户端发出的 HTTP 请求之间可以相互隔离,不存在相互的状态依赖。基于 HTTP 的 ROA,以非常自然的方式来实现无状态服务请求处理逻辑。对于分布式的应用而言,任意给定的两个服务请求 Request 1 与 Request 2, 由于它们之间并没有相互之间的状态依赖,就不需要对它们进行相互协作处理,其结果是:Request 1 与 Request 2 可以在任何的服务器上执行,这样的应用很容易在服务器端支持负载平衡 (load-balance)。

  • 安全操作与幂指相等特性

      HTTP 的 GET、HEAD 请求本质上应该是安全的调用,即:GET、HEAD 调用不会有任何的副作用,不会造成服务器端状态的改变。对于服务器来说,客户端对某一 URI 做 n 次的 GET、HAED 调用,其状态与没有做调用是一样的,不会发生任何的改变。

       HTTP 的 PUT、DELTE 调用,具有幂指相等特性 , 即:客户端对某一 URI 做 n 次的 PUT、DELTE 调用,其效果与做一次的调用是一样的。HTTP 的 GET、HEAD 方法也具有幂指相等特性。

        HTTP 这些标准方法在原则上保证你的分布式系统具有这些特性,以帮助构建更加健壮的分布式系统。

  • RESTful Web Services更容易实现缓存

       众所周知,对于基于网络的分布式应用,网络传输是一个影响应用性能的重要因素。如何使用缓存来节省网络传输带来的开销,这是每一个构建分布式网络应用的开发人员必须考虑的问题。

         HTTP 协议带条件的 HTTP GET 请求 (Conditional GET) 被设计用来节省客户端与服务器之间网络传输带来的开销,这也给客户端实现 Cache 机制 ( 包括在客户端与服务器之间的任何代理 ) 提供了可能。HTTP 协议通过 HTTP HEADER 域:If-Modified-Since/Last- Modified,If-None-Match/ETag 实现带条件的 GET 请求。

          REST 的应用可以充分地挖掘 HTTP 协议对缓存支持的能力。当客户端第一次发送 HTTP GET 请求给服务器获得内容后,该内容可能被缓存服务器 (Cache Server) 缓存。当下一次客户端请求同样的资源时,缓存可以直接给出响应,而不需要请求远程的服务器获得。而这一切对客户端来说都是透明的。

  • 一些缺陷:

  先说成熟度,SOAP发展到现在虽然已经背离了初衷,但是对于异构环境服务发布和调用,以及厂商的支持都已经达到了较为成熟的情况。不同平台,开发语言之间通过SOAP来交互的Web Services都能够较好的互通。

  反观REST,相比于SOAP的权威性协议规范,REST实现的各种协议只能算是私有协议,当然需要遵循REST的思想,在兼容性方面会差很多。

  总的来说SOAP在成熟度上优于REST。

   再说效率,SOAP协议对于消息体和消息头都有定义,同时消息头的可扩展性为各种互联网的标准提供了扩展的基础。REST被人们的重视,其实很大原因是 源于其面向资源接口设计以及操作抽象简化了开发者的不良设计,同时也最大限度的利用了HTTP最初的应用协议设计理念。

  同时, REST还很好的融合Web2.0的很多前端技术来提高开发效率。例如很多大型网站开放的REST风格的API都会有多种返回形式,除了传统的xml作为数据承载,还有JSON,RSS,等形式。

  因此,相对于SOAP, REST的效率更胜一筹。

  最后说安全性,SOAP在安全方面是通过使用XML-Security和XML-Signature两个规范组成了WS-Security来实现安全控制的,当前已经得到了各个厂商的支持。 REST没有任何规范对于安全方面作说明。

四、案例:为Web项目构建一个简单的JSON控制器

      在日常应用中,我们有大量的场合可以使用到RESTful Web Services,包括Web系统间的交互,移动客户端与Web服务器端的通信等。只有在日常工作中更多的实践RESTful,才能更好的理解RESTful Web Services。

   无论项目使用的是哪种数据库后端,JavaScript Object Notation (JSON) 控制器都能简化开发工作。

   假设一个PHP/MySQL 项目:建立一个 MySQL 数据库,创建包含 HTML 的 PHP 视图,根据需要添加 JavaScript 代码和 CSS 文件,连接到数据库,从数据库提取内容来填充视图,等等。如果您熟悉 web 开发,您一定知道分隔功能代码的好处。例如,您知道要避免直接在视图中输入原始 SQL 查询,不会在从数据库提取数据的函数或类中混淆 HTML 标记。

  但是,有时,您的项目可能扩展到您的正常 PHP/MySQL 舒适水平之外。例如,您可能不仅拥有需要来自一个数据库的数据的常规 web 视图,还拥有外部应用程序(比如 Facebook),甚至还拥有访问相同数据的移动设备(比如智能手机)。

  您可能会发现自己身陷这样一种情况:数据库更改,或者要求您处理某种类型的 XML 存储库。在这些情况下,您对 MySQL 的盲目依赖可能会阻碍您完成项目的工作。

  此时可以考虑将一个 RESTful JSON 控制器放置到项目中,将它用作一个虚拟交通警察,负责发送请求并接收来自您的数据源的响应。下面将并展示一种建立控制器的方法。其结果是从一个数据源检索数据的简单方法,检索的数据采用标准化的格式,可以使用 PHP 或 JavaScript 代码轻松解析。

  • 在一个典型的 REST 架构中,一个客户机发送一个请求到服务器,服务器使用请求资源的一个表示来进行响应。资源可以是任何信息对象,比如数据库或文档,它的表示通常是一个格式化的文档(通常是 XML 或 JSON),充当它的当前或被请求状态的一个快照。
  • REST 资源通常使用有意义的 URLs 标识,这些 URLs 接受不同的请求动词 GET、POST、PUT 和 DELETE。这些动词有点类似于许多开发人员都熟悉的 create-retrieve-update-delete (CRUD) 模型。
  • 例如,如果您想检索数据,则使用 GET 请求;要创建数据,则使用 POST 请求;要更新数据,则使用 PUT 请求;最后,要删除数据,则使用 DELETE 请求。
  • 另一个需要考虑的重要因素是响应。RESTful 服务通常在它的响应中提供两个有意义的组件:响应主体本身和一个状态码。许多 REST 服务实际上允许用户指定一个响应格式(比如 XML、CSV、序列化的 PHP 对象或纯文本),方法有两种:一是发送一个 ACCEPT 参数;二是指定一个文件扩展名(例如,/api/users.xml 或 /api/users.json)。其他 REST 服务器,比如您将在这里实现的服务器,拥有硬编码的响应格式。这些格式同样可以接受,只要它们已经有文档记载。
  • 响应代码往往是 HTTP 状态码。这种模式的优点是可以使用知名的现有状态码来标识错误或成功。状态码 201(CREATED)是一个成功 POST 请求的完美响应。错误码 500 表明在您所处的这端(服务端)上发生了错误,但错误码 400 表明客户端上出现了失败(BAD REQUEST)。如果服务器出现故障,将发送错误码 503(SERVICE UNAVAILABLE)。

      一个应用程序拥有的一个数据源包含一些用户信息,名、姓、邮件地址、以及Twitter 帐户。如果您正在设置一个典型的 PHP 应用程序,您需要创建一个 mysql_query() 包装器来使用一个 SQL 查询从数据库提取一个清单。您还需要编写一些 PHP 代码,用于调用那个函数并循环结果集,以便在应用程序视图中显示数据。

  设置一个简单的 REST 控制器,该控制器允许一个针对 /users/list 的、不带任何参数的 GET 请求,然后调用适当的数据库函数并返回一个 JSON 格式的清单。接下来,您的应用程序可以解码那个 JSON 数据,以任何必要的方式循环该数据,以便显示数据内容。

  另外,您可以通过测试检查是否有任何参数被发送到 /users/list。例如,如果您发送一个 GET 请求到 /users/list/1,那么响应将只包含 ID 为 1 的用户的细节。除 JSON 格式外,您甚至可以允许其他格式,比如 XML、CSV 和的 PHP 对象。

  一个 RESTful JSON 控制器对于您的开发工作的作用并非仅仅是在视图和数据源之间放置一个额外的功能层。想想看,您的基本 PHP 视图也许不是请求信息的惟一组件。例如,您可能会使用 jQuery 通过一个 Ajax 接口请求数据,或者,您的用户可能会通过一部智能手机或一个 Facebook 应用程序请求数据。

  在这些情况下,一个接收请求并以一种容易理解(和预测)的格式提供响应的 RESTful 接口可能会极大地简化您的开发工作。作为负责 PHP 视图(或者甚至 iPhone 应用程序)的开发人员,您可以发送一些请求到一个 URL 并接收一组预期响应。在 JSON 控制器的另一面,应用程序可以被钩挂(hook)到 MySQL、PostgreSQL、一个 XML 文件存储库、或者什么也不挂。

     1. 首先创建一个简单的事件数据库架构(MYSQL)

CREATE TABLE `events` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARYKEY ,
`title` VARCHAR( 255 ) NOT NULL ,
`address` VARCHAR( 255 ) NOT NULL ,
`start_time` DATETIME NOT NULL ,
`description` TEXT NOT NULL
);

    2. 创建一个典型 PHP 模型文件,它连接到这个数据库并使用一个 SQL 查询来识别事件。

$SERVER = 'name';
$USER = 'username';
$PASS = 'pw';
$DATABASE = 'dbname';

if (!($mylink = mysql_connect($SERVER, $USER, $PASS)))
{
    echo "Sorry, could not connect to DB. Contact your sysadmin for help!";
    exit;
}
mysql_select_db( $DATABASE );

class Events{
    function get_events($day){
    $ret_array = array();
    $sql ="select id,title,address,start_time,description
    from events where start_time like '$day%'
    order by start_time asc";
    $result = mysql_query($sql);

    while($data = mysql_fetch_object($result)){
    $obj['id'] = $data->id;
    $obj['title'] = $data->title;
$obj['address'] = $data->address;
$obj['start_time'] = $data->start_time;
$obj['description'] = $data->description;

$ret_array[] = $obj;
}
return $ret_array;
}
}
    
View Code

     对这个函数的一个简单调用时,您将得到如下所示的结果。

$EVENT = new Events;
$today = '2010-06-17';
$events = $EVENT->get_events($today);
print_r($events);
/* results in
Array
    ([0] => Array(
     [id] => 2
     [title] => Event #2
     [address] => 156 My Avenue, MyTown, USA 78727
     [start_time] => 2010-06-17 11:30:00
     [description] => Join us for lunch to hear
     FABULOUS SPEAKER.
     )
    [1] => Array(
     [id] => 1
     [title] => Event #1
     [address] => 123 My Street, Anytown USA 78727
     [start_time] => 2010-06-17 15:30:00
     [description] => A great event! Hope to see you there!
    )
 )
*/
  

    通过 json_encode() 运行相同的代码,将得到一个可移植的 JSON 对象(如 所示)

[
  {"id":"2",
  "title":"Event #2",
  "address":"156 My Avenue, MyTown, USA 78727",
  "start_time":"2010-06-17 11:30:00",
  "description":"Join us for lunch to hear FABULOUS SPEAKER. "
  },
  {"id":"1",
  "title":"Event #1",
  "address":"123 My Street, Anytown USA 78727",
  "start_time":"2010-06-17 15:30:00",
  "description":"A great event! Hope to see you there!"
  }
]

目标是构建这样一个简单的控制器:它知道应该运行哪个模型和函数,然后返回一个 JSON 对象作为响应,这个响应可用于事务的远端。这个控制器非常简单,看起来如下所示。将如下所有代码粘贴到一个名为 json.php 的文件中。

class JSON{
    var $response = '';
    function JSON($model,$function,$params){
        $REQUEST = new $model;
        $data = $REQUEST->$function($params);
        $this->response = json_encode($data);
    }
}            

     调用的模型,实例化 JSON 类,然后传入 3 个参数:模型的类名、要运行的函数、以及该函数的参数。这个类然后调用那个函数并获取一个响应,该响应通过 json_encode() 运行。   

   3. 最后一步是创建包含对 JSON 数据的请求的文件。这个特殊的文件(您可以称之为 listing.php)可以设置为接收 3 个 GET 变量(模型、函数和参数各一个),然后将这些变量传递给 JSON 类(如清单 7 所示)

请求代码

//this is the code that contains the model
require 'events.php';
//this is the JSON controller
require 'json.php';
//pass in your three GET parameters
$MODEL = $_GET['model'];
$FUNCTION = $_GET['function'];
//check to see if param is passed in
//if not, use today's date in this instance
if (isset($_GET['param'])){
    $PARAM = $_GET['param'];
}else{
    $PARAM = date("Y-m-d");
}
//invoke
$JSON = new JSON($MODEL,$FUNCTION,$PARAM);
//access the response variable
echo $JSON->response;

       可以将这个文件加载到一个浏览器中,并获取一个 JSON 对象。再通过 json_decode() 将这个 JSON 对象发送回去,使用 JavaScript 代码处理它,或者让它保持原样。

  整个这个流程的一个甚至更好的方法是创建一个更紧密模拟 RESTful 服务器的路径结构。例如,可以创建一个名为 events/today 的目录结构,该结构包含一个名为 index.php 的文件。通过将您的浏览器指向 /events/today,无需传入任何 GET 变量,您就可以基于如下的代码取回一个 JSON feed。
      /events/today/index.php 中的代码

require '../../events.php';
require '../../json.php';
$MODEL ="Events";
$FUNCTION ="get_events";
$PARAM = date("Y-m-d");
//invoke
$JSON =new JSON($MODEL,$FUNCTION,$PARAM);
echo $JSON->response;
//prints out
[
    {"id":"3",
     "title":"Test Event 3",
     "address":"111 Main Street, Austin TX 78727",
     "start_time":"2010-06-10 15:15:00",
     "description":"Testing 456."
    }
]

Using this method, you can simplify some of the data extraction requirements for the application and support your view. Developers do not need to remember all the details of the underlying database, on the contrary, they can easily hit URLs and receive a response they are looking to continue their work.

reference:

Reproduced in: https: //www.cnblogs.com/JoannaQ/p/3247077.html

Guess you like

Origin blog.csdn.net/weixin_33766168/article/details/93056595