public
Created

subdomain component for cakephp that depends on a model

  • Download Gist
subdomain.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
<?php
class SubdomainComponent extends Object {
 
var $__settings = array(
'base' => 'example.com',
'domains' => array(),
'param' => 'subdomain',
'redirect' => true,
'redirectTo' => 'http://example.com',
'model' => 'DomainPrefix',
'method' => 'getSubdomain',
'cookie' => false,
);
var $components = array('Cookie');
var $Controller = null;
/**
* Called before the Controller::beforeFilter().
*
* @param object A reference to the controller
* @return void
* @access public
* @link http://book.cakephp.org/view/65/MVC-Class-Access-Within-Components
*/
function initialize(&$controller, $settings = array()) {
$this->__settings = array_merge($this->__settings, $settings);
$this->Controller = $controller;
if (!in_array(strtolower($_SERVER['HTTP_HOST']), $this->__settings['domains'])) {
$urlParts = explode('.', strtolower($_SERVER['HTTP_HOST']));
$subdomain = ($urlParts[0] == 'www') ? $urlParts[1] : $urlParts[0];
 
if (($record = Cache::read("subdomain.{$subdomain}")) === false) {
$this->Controller->loadModel($this->__settings['model']);
$record = $this->Controller->{$this->__settings['model']}->{$this->__settings['method']}($subdomain);
if ($record) {
Cache::write("subdomain.{$subdomain}", $record);
}
}
 
if ($record) {
// Cool cause now we can check the subdomain in every action
$this->Controller->params[$this->__settings['param']] = $record;
 
if ($this->__settings['cookie']) {
$this->Cookie->domain = '.' . $this->__settings['base'];
$this->Cookie->key = Configure::read('Security.salt');
 
if (!class_exists('Set')) {
App::import('Core', 'Set');
}
 
$this->Cookie->write('subdomain', Set::classicExtract($record, $this->__settings['cookie']));
}
return;
}
// Optionally, you could redirect to an error page or something
$this->Controller->params[$this->__settings['param']] = null;
if ($this->__settings['redirect'] && $this->__settings['redirectTo']){
$this->Controller->redirect($this->__settings['redirectTo'], 404);
}
}
}
 
function redirectOnCookie() {
if (!empty($this->Controller->params[$this->__settings['param']])) {
return;
}
$this->Cookie->domain = '.' . $this->__settings['base'];
$this->Cookie->key = Configure::read('Security.salt');
$subdomain = $this->Cookie->read('subdomain');
if ($subdomain) {
$this->Controller->redirect('http://' . $subdomain . '.' . $this->__settings['base']);
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.