Loadsys

LoadStr - A Loadsys Blog

A Web Development Company Specializing In Standard-Based Web Design and the CakePHP Framework.

Posts Tagged ‘CakePHP Developers’

CakePHP Metadata Plugin

Tuesday, April 12th, 2011

The metadata plugin simplifies the setting of HTML page meta data. Web site meta tags are often the same for every page, but a few could vary between requests. The purpose of the metadata plugin is to eliminate view or layout logic for setting meta tags data. It is also meant to encapsulate the static meta tag content from controller logic, while still allowing for tags to be overwritten conditionally in the controller.

There is a simple way to use this plugin without much maintenance for the duration of the project. After including the plugin, simply include the component.

public $components = array(‘Metadata.Metadata’);

The meta tags data can be completely encapsulated from the controller logic by including a metadata.php file in app/config/. This file will automatically get included and meta tags can be created from the data contained. In the metadata file, site global, controller global and action specific properties can be set (in the case of the PagesController, the page file can be set instead of actions).

// app/config/metadata.php

$metadata = array(
	‘_all’ => array(
		‘description’ => ‘Site wide description’
	),
	‘pages’ => array(
		‘_all’ => array(
			‘description’ => ‘All pages_controller pages description’
		),
		‘home’ => array(
			‘description’ => ‘Home page description’
		)
	),
	‘controller_name’ => array(
		‘_all’ => array(
			‘description’ => ‘All controller_name actions description’
		),
		‘action’ => array(
			‘description’ => ‘controller_name/action description’
		)
	)
);

By having all of the meta data in the a config, the data can be semi dynamic for different pages without having to build controller setting logic or have any additional logic in the view. In some cases, though, it will be necessary to set a meta tag data from within the controller. The Metadata component exposes a method for setting meta tag data manually. Any data set this way will overwrite data that for the same key that might already exist.

$this->Metadata->metadata(‘description’, ‘Manually set description’);

or

$this->Metadata->metadata(‘description’, array(
‘content’ => ‘Manually set description’,
‘http-equiv’ => ‘content-type’
));

Note: Metadata can be set as an array like the second example above, even in the metadata.php, as long as a content key exists in the array. All additional keys will be passed as attributes in the helper.

So far, so good. We can now get rid of all the logic in the controllers regarding metadata. We can also get rid of any sets in the view that set data for the layout to render. All the metadata information is set in the metadata file, or overwritten in special cases in the controller. But how is all of this metadata rendered? Short answer:

<?php echo $this->MetaData->meta(); ?>

The Metadata plugin comes with a Helper also named Metadata. The helper is automatically added to the controllers $helpers property. While adding the helper, the component also passes along all of the metadata keys that have been added up to that point (this happens in the Metadata component beforeRender()).

By not specifying any parameters, the helper’s metadata() method will loop through all data passed in from the controller, and render the data using Html->meta(). The metadata method can also take parameters and pass them along to the Html->meta() method if you’d like to stick to a single method for handling meta tags data.

Another method exposed by the metadata helper is the title() method. If at any point, metadata is set with the key “title”, that data is set aside in the helper. To render the title, use the title() method. The first two parameters are a default title, and a boolean merge option. If a default title is passed and merge is set to true, the return will be the combination of the title set in metadata and the passed in default title (an example would be a site wide title and a post, newsletter, etc title contained in the data layer).

The Metadata plugin is meant to be an alternative to having to manage metadata database tables. In many sites, a full model/behavior solution may be too much. This plugin was the solution that best fit one of our projects, and we hope it comes in handy for some of you.

Then code can be downloaded or cloned from here: https://github.com/joeytrapp/metadata

CakePHP JSON API Plugin (Code Release)

Wednesday, October 20th, 2010

Loadsys has released a CakePHP plugin to aid in the creation of JSON APIs. This plug-in contains a few helpful classes for both the API side and a CakePHP JSON API consumer. This post will cover one of the pieces from that plug-in called the Server Response Component.

Installation

cd app/plugins
git clone git@github.com:loadsys/JSON-API.git json_api

GitHub Repo URL:  http://github.com/loadsys/JSON-API

Setup

In the controller that will serve json (or app_controller if the whole app is serving json) add this to the components array:

public $components = array(‘json_api.ServerResponse’);

Prerequisites

This line of code must be in the app/config/routes.php:

Router::parseExtensions(‘json’);

Overview

The purpose of the Server Response Component is to set appropriate HTTP headers for the API’s response to a consumer’s request. By following some REST conventions, there is little extra work for the API developers.

To set data to be sent with the response, just set it like you normally would in the controller. Just before output of the JSON object, the data set is added to another array under the key ‘response’. Additional information is in the array as siblings to the ‘response’ key, such as controller, action, plugin, status code number, status code string, response message and boolean success.

Additionally, the component will check for pagination settings in the $controller->params[‘paging’]. If they do exist, a header will be set for the different paging settings.

The one important thing to remember is that you must manually set the methodType to a valid method type in the action method. Valid methodType’s are view, add, edit and delete. All that needs to be called for methods that are not named one of the valid method names (i.e. ‘search’) is $this->ServerResponse->setMethodType(‘valid method type’); (in the case of ‘search’, you would set the methodType to ‘view’).

Methods

setMethodType/methodType

Getter and Setter for the $methodType property. The methodType is automatically determined if using a basic CRUD method (view, index, add, edit, delete). If method being called is not one of those, the method type must be explicitly set to a valid type: (view, add, edit, delete). The reason for this is that based on the methodType and the methodSuccess, the responseCode is set to the appropriate REST Convention.

$this->ServerResponse->setMethodType(‘view’);

setMethodSuccess/methodSuccess

Getter and Setter for the $methodSuccess property. The methodSuccess is set to true by default, so it only needs to be set to false when the controller method fails. Optionally, a second parameter can be sent with the setMethodSuccess() method to also set the responseMessage property. See responseMessage below for more information.

$this->ServerResponse->setMethodSuccess(false, $message);

setResponseCode/responseCode

Getter and Setter for the $responseCode property. If the responseCode is set before the the method for generating one is called, then the code that exists will be used. Response codes are generated during the component beforeRender callback.

$this->ServerResponse->setResponseCode(200);

setResponseMessage/responseMessage

Getter and Setter for the $responseMessage property. Same as the resonseCode, if the responseMessage is already set before the responseCode generator is called, then the existing message is used. Otherwise, generic messages are created based on methodType if the methodSuccess is false. If methodSuccess is true and no message is explicitly set, then the message will be null.

$this->ServerResponse->setResponseMessage($message);

Callbacks

string beforeCompareMethodType(string $methodType)

In the components beforeRender method, the methodType, that was determined in initialize method, is checked against valid method types and the request type. If the method type does not match a valid method type for the right request type, the response code is set to 405 Method Not Allowed and the response is rendered. An example would be if the method type was ‘edit’, but the request type was GET. This call back is called just before the comparison, and is the last chance to modify the method type. Whatever string is returned is set to the methodType property.

array beforeSetResponseInfo(array $params)

Just after the response code is automatically generated, but before the value is set to properties, this callback is called. The array passed in contains 3 keys: ‘status’, ‘message’, ‘success’. This is the last chance to modify responseCode, responseMessage and methodSuccess. Return an array with the same keys as the parameter array.

array beforeJsonRender(array $array)

This is the last method called before the component echo’s the JSON encoded response data and exits. The array passed into the method is the return data that will be set to the ‘response’ key in the array that gets json_encoded(). Whatever array is returned will be set in place of the return data that currently exists.

Code Example

<?php

class ExampleController extends AppController {

      public $components = array(‘json_api.ServerResponse’);      
      public function index() {
            $var = $this->paginate();
            if (empty($var)) {
                  $this->ServerResponse->setMethodSuccess(false, ‘Example empty’);
            }
            $this->set(compact(‘var’));
      }
}
?>

 

Joey Trapp
Web Developer
Loadsys

Close
E-mail It