Zend CDN Integration

The Zend CDN integration requires to implement a little plugin to point the URLs of your assets to KeyCDN. We recommend to read the details on how to create a Zend plugin.

  1. Create a pull zone before you start the Zend CDN integration.
  2. Create the following Zend plugin to create links that point to your KeyCDN URL (replace cdn.example.com with your CDN URL).
    class KeyCDN_Plugin extends Zend_Controller_Plugin_Abstract {
        public function preDispatch(Zend_Controller_Request_Abstract $request) {
        
            // enable CDN links for development env
            $enable_cdn_dev = (bool) true;
            
            // KeyCDN URL or Zonealias
            $cdn_hostname = 'cdn.example.com';
    
            if((APPLICATION_ENV == 'production') || $enable_cdn_dev)) {
                // SSL or not
                if($request->isSecure()) {
                    Zend_Registry::set('cdn_protocol', 'https');
                } else {
                    Zend_Registry::set('cdn_protocol', 'http');
                }
    
                Zend_Registry::set('cdn_on', true);
                Zend_Registry::set('cdn_hostname', $cdn_hostname);
            } else {
                Zend_Registry::set('cdn_on', false);            
            }
    
            return true;
    
        }
    }
  3. Create a Zend view helper.
    class KeyCDN_Helper extends Zend_View_Helper_Abstract {
        public function cdn($url) {
            if(empty($url))
                throw new Exception('Path is missing');
    
            $pattern = '/^http/i';        
            if(preg_match($pattern, $url))
            {
                throw new Exception('Invalid usage. ' .
                    'Use: /htdocs/images instead of the full URL ' .
                    'http://example.com/htdocs/images.'
                                   );
            }
    
            $pattern = '|^/|';        
            if(!preg_match($pattern, $url)) {
                $url = '/' . $url;
            }
    
            if(!Zend_Registry::get('cdn_on')) {
                return $url;
            } else {
                $cdn_hostname = Zend_Registry::get('cdn_hostname');
                $cdn_protocol = Zend_Registry::get('cdn_protocol');
                $uri = $cdn_protocol . '://' . $cdn_hostname . $url;
    
                return $uri;
            }    
        }    
    }
  4. Finally, use the view helper in your Zend project (e.g. in your views or template).
    <img alt="Your alt text" src="<?php echo $this->cdn('/htdocs/images/your-image.jpeg'); ?>" />
  5. Verify in the HTML source code if the links are pointing to the CDN URL.

Leave A Comment?