Why Use a CDN in Phalcon?
Phalcon is a high-performance PHP framework renowned for its low resource consumption and rapid execution. By integrating a Content Delivery Network (CDN) with Phalcon, you can further enhance your application's performance by delivering static assets like images, CSS, and JavaScript files from servers closer to your users. This reduces latency, decreases server load, and improves page load times, leading to a better user experience and potentially higher search engine rankings.
Before you start
- Before you take any steps please back up your files and database.
- In the following, we will integrate a CDN service using the CDN domain cdn.mycompany.com Please visit the Services/How-To section to obtain your CDN domain.
- To integrate a CDN service on https:// website the CDN service must have SSL enabled.
- If your website embeds custom fonts then please first enable CORS for them.
- Before you take any steps please make sure that your CDN domain is ready-to-use here.
Create CDN Static service
Please refer to Creating a CDN Static service for more details.
How to Enable CDN in Phalcon
Follow these steps to configure Phalcon to serve static assets through your CDN at https://cdn.mycompany.com.
Method I - Integration using setStaticBaseUri()
<?php $url = new Phalcon\Mvc\Url(); // Dynamic URIs remain unchanged $url->setBaseUri('/'); // Static resources are served from the CDN $url->setStaticBaseUri('https://cdn.mycompany.com/');
Method II - Integration using collections
<?php $css = $this->assets->collection('header'); $scripts = $this->assets->collection('footer'); if ($config->environment == 'development') { $css->setPrefix('/'); $scripts->setPrefix('/'); } else { $cdnURL = 'https://cdn.mycompany.com/'; $css->setPrefix($cdnURL); $scripts->setPrefix($cdnURL); } $css->addCss('css/bootstrap.min.css') ->addCss('js/custom.css'); $scripts->addJs('js/jquery.js') ->addJs('js/bootstrap.min.js');
Method III - Simple integration
<?php $cdnURL = 'https://cdn.mycompany.com/'; $this->assets ->addCss($cdnURL.'css/custom.css', false);
Notes
- View HTML source code of your web pages to verify that you are using CDN, you should see source attribute of your images, CSS, JavaScript, etc. beginning with your CDN domain.
- Don't see your CDN domain in the source code of your web pages? If your website is using any cache plug-in/mechanism then you might want to clear/flush its cache.
- Having trouble with custom fonts? Please refer to Using custom fonts with CDN - setting CORS for more details.
- Still having trouble? Check your CDN URLs using our content check tool or please refer to Debugging a CDN service for more hints.
- Can you improve this guide or write a new one for software we haven't covered? Help us expand our CDN integrations section and earn $50 in CDN credit! Contact us to contribute.