A fusion of technology, music, and geekyness.
Currently Browsing: CakePHP

CakePHP eCommerce Done Right: Mocha Shopping Cart

Mocha Shopping Cart

Mocha Shopping Cart

A few months back I posted on CakePHP eCommerce and the lack of good solutions. Well that is now no longer the case. I would like to be one of the first people to introduce you to Mocha Shopping Cart. We have been working day and night (literally) to come up with a solution for the small and medium sized business owners to sell their products online easily. We also have geared Mocha to be extend-able and easy for CakePHP designers and developers to add in their own twists for clients.

Mocha is written entirely in CakePHP and jQuery and is certainly the best CakePHP eCommerce app out there. Why do I say that?

Mocha Shopping Cart is…

  • Fully hosted, secure, pre-installed
  • Very easy to set up and configure
  • Themable and Modular (Plug ins docs in the works)
  • Works with most popular payment and shipping apis (UPS, USPS, Authorize.net, Paypal, etc.)
  • Charges no transaction fees and no setup fees

If you still don’t believe me, Mocha is offering a limited time only Pre-Launch coupon code that gives you the first month FREE. You can try it for yourself and see how you like it. I think you will agree that it beats CakeCart and BakeSale, HANDS DOWN! And no, Mocha is not free (after the first 30 days). The costs help to speed up development, pay for server and hosting fees, and pay for that cup of coffee that us developers need when its 8 AM and we are having to talk with <insert_API_name_here> first thing in the morning.

Official Website: Mocha Shopping Cart
Blog with coupon code: Get a free trial of Mocha Shopping Cart


Easy JSON with CakePHP and jQuery

I am not sure if this is the fanciest way to get the job done but it works REALLY well. What job am I referring to? I am referring to outputting data as JSON in a CakePHP view and then parsing it in a jQuery AJAX response. Its fairly easy to accomplish with the JSON parser provided by json.org. Scroll to the bottom and download/include json2.js.

Controller example:

				$sizeArray = getimagesize('/path/to/really_cool_image.jpg');

				$outputArray = array(
					'file' => 'really_cool_image.jpg',
					'width' => $sizeArray[0],
					'height' => $sizeArray[1],
				);

				$this->set('result', $outputArray);

				$this->render(null, 'ajax');

AJAX View example:

Configure::write('debug', 0);
echo $javascript->object($result);

jQuery AJAX response handler example:

	  function(response, status) {
	  		imageDetails = JSON.parse(response);
	  		imageName = imageDetails.file;
	  }

CakePHP: Including Models inside your Controller

There are currently three methods for including and using models inside your controller. I am referring to the case when your controller does not belong to a model or or the model is not related to the model inside the controller you are working in. Although this case should be extremely rare, it seems to happen to me a lot. This post is basically a re-summary of Gwoo’s response in the CakePHP Google Groups discussion.

1. Controller::loadModel();
This method actually calls ClassRegistry::init() and saves the instance of the model as a parameter in the controller.

Example:

Controller::loadModel('Car');
$cars = $this->Car->find('all');

2. ClassRegistry::init()
This method creates an instance of the Model and returns it for use.

Example:

$car = ClassRegistry::init('Car');
$cars = $car->find('all');

3. App:import() (not recommended)
This method only includes the file. This requires you to create an instance each time.

Example:

App::import('Car');
$car = new Car();
$cars = $car->find('all');

As you can see this is really simple and basic stuff. However, I felt the need to re-post this information. If for nothing else, I will be using this as a reference point for myself :)

Update 5/27/09: Miles Johnson has a nice write up on this on his blog


CakePHP Character Encoding Checklist

I was having some issues today with character encoding and I thought I’d post about it. There are three elements that you need to make sure you have if you want to properly use UTF-8 character encoding in your Cake app. My issue was that I did not have #2, although adding #1 didn’t hurt either.

1. Database Config

Add ‘encoding’ => ‘utf8′ to app/config/database.php

	var $default = array(
		'driver' => 'mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'user',
		'password' => 'password',
		'database' => 'database',
		'encoding' => 'utf8'
	);

2. Make sure your layout has the charset line in the

	<head>
	 	<?php echo $html->charset(); ?>
	 	Other elements...
	</head>

3. This one is set by default, but make sure App.encoding is set in app/config/core.php

/**
 * Application wide charset encoding
 */
	Configure::write('App.encoding', 'UTF-8');

And thats it!


Authenticating a CakePHP App Against a CakePHP Webservice

Update 03/27: I fixed the code formatting and added the Cakeservice Behavior

Rick and I figured out a nice solution to having one CakePHP application authenticate a user (and thus acodeessing data) from a different CakePHP application setup as an XML webservice. The authenticating app POSTs an XML string to the web service, which is automatically parsed by CakePHP and put into $this->data. It is then used in a custom xmlLogin() function that uses the Auth Component to log the user in. This solution handles all cookies appropriately so you wont have to worry about much there.

This solution would most likely be better if it were a DataSource instead of a ModelBehavior. We chose a ModelBehavior first because we are not familiar with writing custom data sources yet and wanted a simple, quick, and effective solution. This is a work in progress so I hope to expand on it more later and eventually have it act as a data source instead.

I am assuming:

* You have the latest CakePHP (1.2.1) installed and connected to the database
* You have the Auth Component installed and configured to the defaults
* You have at least one user record with a valid password hash
* You have the XML Helper enabled in your app_controller.php

Step 1: Make CakePHP Act as a Webservice (service side)

1. Add similar code in app/config/routes.php:

Router::mapResources(array('users', 'acodeounts'));
Router::parseExtensions();

2. Add RequestHandler to your components array in app_controller:

var $components = array('RequestHandler');

3. Add an xml folder to each view directory, with .ctp files for each action you would like to have. This is an example of app/views/users/xml/index.ctp:

<users>
<?php echo $xml->serialize($users); ?>
</users>

See the CakeBook for more information on step 1.

Step 2: Setup CakePHP Errors for Reponse XML (service side)

We decided to use the built in custom errors system inside Cake for displaying Reponse XML for Webservice calls. I know that not all XML responses will be errors (it should actually be the opposite) but I like the way CakePHP handles custom error pages so we leveraged this functionality for this topic.

1. Create app/views/errors/serviceresponse.ctp

<responses>
  <response>
    <code><?php echo $errorCode; ?></code>
    <message><?php echo $errorMessage; ?></message>
  </response>
</response>

2. Create app/app_error.php

<?php
Class AppError extends ErrorHandler {

    function serviceResponse($params) {
        $this->controller->set('errorCode', $params['errorCode']);
        $this->controller->set('errorMessage', $params['errorMessage']);
        $this->controller->layout = 'xml/default';
        $this->_outputMessage('serviceresponse');
    }
}
?>

Now this can be called by using this code in the controller as needed

$this->cakeError('serviceResponse', array('errorMessage' => $errorMessage, 'errorCode' => $errorCode));

Step 3: Create Custom Login Function (service side)

1. Add xmlLogin() to app/controllers/users_controller.php

    function xmlLogin() {
        // Verify request is from a webservice
        if ($this->Session->check('webserviceRequest')) {
            $this->Session->delete('webserviceRequest');

            // Default response
            $errorMessage = 'Login is required to acodeess this resource';
            $errorCode = 'login_required';

            // Check to see if data was posted
            if (!empty($this->data)) {
                // Parse the XML object into an array
                $data = Set::reverse($this->data);

                // Hash the passwords
                $this->data = $this->Auth->hashPasswords($data['Users']);

                // Login
                if($this->Auth->login($this->data)) {
                    $errorMessage = 'Logged in';
                    $errorCode    = 'auth_sucodeess';
                } else {
                    $errorMessage = 'Invalide username or password';
                    $errorCode = 'auth_fail';
                }

            }

            // Generate the response
            $this->cakeError('serviceResponse', array('errorMessage' => $errorMessage, 'errorCode' => $errorCode));
        }
    }

2. Modify the default login()

    function login() {
        if ($this->Session->check('webserviceRequest')) {
            $this->Session->delete('webserviceRequest');

            $this->cakeError('serviceResponse', array('errorMessage' => 'Login is required to acodeess this resource', 'errorCode' => 'login_required'));
        }
    }

3. Add in the webserviceRequest check to beforeFilter() in app/app_controller.php

    function beforeFilter() {
        if ($this->params['url']['ext'] == 'xml') {
            $this->Session->write('webserviceRequest', true);
        }
    }

4. Allow xmlLogin() to bypass Auth. Add the following to the top of your users_controller.php:

	var $preAuth = array();
	function beforeFilter() {
		parent::beforeFilter();

		$this->preAuth['password'] = $this->data['User']['password'];
		$this->Auth->allow('loginTest');
	}

Step 4: Install the Cakeservice Behavior (app side)

1. Download cakeservice.php and put it in app/models/behaviors/cakeservice.php

<?php
/**
 * A simple WebService Behavior class that eases requests to foreign pages
 * Entirely PHP based, does not require and modules or cURL.
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * Based on the WebserviceModel authored by Felix Geisendörfer (http://debuggable.com)
 * Based on WebService Behavior by Mark Story (mark-story.com)
 *
 * @author DualTech Services, Inc. (dual-tech.com)
 */
App::import('Core', 'Socket');

class CakeserviceBehavior extends ModelBehavior {
	var $_headers, $_path, $response, $Socket;
	var $cookies = array();

	function request(&$Model, $params = array()) {
		// Setup the connection
		if (!empty($params['url'])) {
			$this->serviceConnect($Model, $params['url']);
		} else {
			return false;
		}

		$postHeaders = array(
			'Host' => 'jadams.bounceme.net',
			'Connection' => 'Close',
		);

		$requestMethod = 'POST';
		if (empty($params['data'])) {
			$requestMethod = 'GET';

		} else {
			$params['data'] = '<?xml version="1.0" encoding="UTF-8" ?>' . $params['data'];
			$postHeaders = array_merge($postHeaders, array('Content-Length' => strlen($params['data']), 'Content-Type'	=> 'text/xml'));
		}

		$this->_formatHeaders($postHeaders);

		$request = "$requestMethod {$this->_path} HTTP/1.0\r\n";
		$request .= $this->_headers . "\r\n";
		$request .= "\r\n";
		if (!empty($params['data'])) {
			$request .= $params['data'];
		}

		$this->Socket->write($request);

		$response = '';
		while ($data = $this->Socket->read()) {
			$response .= $data;
		}

		$this->_parseResponse($response);

		if (array_key_exists('Location', $this->response['headers'])) {
			//$this->serviceConnect($Model, $this->response['headers']['Location']);
			$params['url'] = $this->response['headers']['Location'];
			$this->request($Model, $params);
		}
		return $this->response['body'];
	}

/**
 * Connect the Behavior to a new URL
 *
 * @param string $url The URL to connect to.
 * @param array $options Options Array for the new connection.
 * @return bool success
 **/
	function serviceConnect(&$Model, $url) {
	    $options = array(
	        'timeout' => 30,
	        'persistent' => false,
	        'defaultUrl' => null,
	        'port' => 80,
	        'protocol' => 'tcp',
	        'followRedirect' => true
	    );		

		$path = $this->_setPath($url);
		$options['host'] = $path['host'];

		if ($this->Socket === null) {
			$this->Socket = new CakeSocket($options);
		} else {
			$this->serviceDisconnect($Model);
			$this->Socket->config = $options;
		}
		return $this->Socket->connect();
	}

/**
 * Disconnect / Reset the Webservice Socket.
 *
 * @return boolean
 **/
	function serviceDisconnect(&$Model) {
		if ($this->Socket !== null) {
			$this->Socket->disconnect();
			$this->Socket->reset();
		}
	}

/**
 * Formats Additional Request Headers
 *
 * @return void
 **/
	function _formatHeaders($headers = array()) {
		$headers['User-Agent'] = 'CakeserviceBehavior';
		$headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
		$headers['Accept-Language'] = 'en-us,en;q=0.5';

		// Load cookies
		$headers['Cookie'] = '';
		foreach($this->cookies as $cookieKey => $cookieData) {
			$headers['Cookie'] .= $cookieKey . '=' . $cookieData['value'] . '; ';
		}

		foreach ($headers as $name => $value) {
			$tmp[] = "$name: $value";
		}
		$header = implode("\r\n", $tmp);
		$this->_headers = $header;
	}	

/**
 * Parse the Reponse from the request, separating the headers from the content.
 *
 * @return void
 **/
	function _parseResponse($response) {
		$headers = substr($response, 0, strpos($response, "\r\n\r\n"));
		$body = substr($response, strlen($headers));

		//split up the headers
		$parts = preg_split("/\r?\n/", $headers, -1, PREG_SPLIT_NO_EMPTY);
		$heads = array();
		for ($i = 1, $total = sizeof($parts); $i < $total; $i++ ) {
			list($name, $value) = explode(': ', $parts[$i]);
			$heads[$name] = $value;
		}

		if (array_key_exists('Set-Cookie', $heads)) {
			// Save cookies

			$cookies = array();
			foreach ($heads as $headerKey => $headerValue) {
				if ($headerKey == 'Set-Cookie') {
					$parts = split('; ', $headerValue);

					$cookieKey = '';
					foreach ($parts as $index => $part) {
						list($key, $value) = split('=', $part);

						if ($index == 0) {
							$cookieKey = $key;
							$cookies[$cookieKey]['value'] = $value;
						} else {
							$cookies[$cookieKey][$key] = $value;
						}
					}
				}
			}

			$this->cookies = $cookies;
		}

		$this->response['headers'] = $heads;
		$this->response['body'] = trim($body);
	}	

/**
 * Set the host and path for the webservice.
 * @param string $url The complete url you want to connect to.
 * @return array Host & Path
 **/
    function _setPath($url) {
        $port = 80;
        if (preg_match('/^https?:\/\//', $url)) {
            $url = substr($url, strpos($url, '://') + 3);
        }
        if (strpos($url, '/') === false) {
            $host = $url;
            $path = '/';
        } else {
            $host = substr($url, 0, strpos($url, '/'));
            $path = substr($url, strlen($host));
        }
        if ($path == '') {
            $path = '/';
        }

        $this->_path =$path;
        return array('host' => $host, 'path' => $path, 'port' => $port);
    }

    function setCookies(&$Model, $cookies) {
    	$this->cookies = $cookies;
    }

    function getCookies(&$Model) {
    	return $this->cookies;
    }
}
?>

2. Add cakeservice to your actsAs array in each model you want to utilize it:

var $actsAs = array('cakeservice');

3. Overwrite the default login() function

	function login() {
		if (!empty($this->data)) {
	        $user = array(
	            'Users' => array(
	                'User' => array(
	                    'username'    => $this->data['User']['username'],
	                    'password'    => $this->preAuth['password'],
	                )
	            )
	        );		

	        // Convert the data to XML
	        App::import('Xml');
	        $xml = new Xml($user);

	        // Load existing cookies, if any, for the webservice call
	        if($this->Session->check('apiCookies')) {
	            $this->User->setCookies($this->Session->read('apiCookies'));
	        }

	        // Web service communication
	        $result = $this->User->request(array(
	            'data'    => $xml,
	            'url'    => 'domain.example/path_to_cake/users/xmlLogin.xml',
	        ));

	        // Save the cookies from the web service
	        $cookies = $this->User->getCookies();
	        if(!empty($cookies)) {
	            $this->Session->write('apiCookies', $cookies);
	        }

			$xml = new Xml($result);
			$response = Set::reverse($xml);

			if (isset($response['Responses']['Response']['Data']['User']['id'])) {
				$this->Session->write('Auth.User', $response['Responses']['Response']['Data']['User']);
				$this->Session->setFlash('Successfully logged in.');
				$this->redirect('/');
			} else {
				$authData = $this->Session->read('Message.auth');
				$authData['message'] = $response['Responses']['Response']['message'];
				$this->Session->write('Message.auth', $authData);
			}
		}
	}

Please feel free to post any comments or questions you may have.


« Previous Entries

Powered by Wordpress | Designed by Elegant Themes