Levearage CloudwaysCDN To Add More Power To PHP Frameworks

in cdn •  6 years ago 

CDN or content delivery network ensures the fastest delivery of content and assets to the users. People don’t like slow sites. if your website is facing too much load time and loading the assets lazily, you need to take serious steps to improve your website. Normally the websites are monetized for the various audience located in different regions of the world so when visitors come from different regions they face latency while browsing your website content. To reduce this latency applying CDN in the website is the best option.

Now a days CDN becomes the necessary component to integrate in web applications for witnessing the fastest performance. Well what if you don’t have CDN in your website? Let’s have a look at this picture showing the comparison of CDN and non-CDN based sites:

image9.png

When you run a website without CDN you serve content from the ingle centralized server. Every visitor will be entertained by this server only. But CDN allows you to create global server locations geographically and serve the content from the nearest location of the visitor.

The global data centers are consist of two main things, POPs and caching edge servers. PoP are data centers which serves the content geographically to reduce the latency while Edge servers are the ones which store and deliver cached files to accelerate website load times and reduce bandwidth consumption. Caching Edge servers contain multiple storage drives along with high amounts of RAM resources to store the most frequently accessed items.

How CDN Actually Works

We have so many CDN options available these days every CDN system work on unified principal. Actually CDN caches all the content (such as text, images) on multiple geographical locations which are called PoPs. Each PoP contains number of servers responsible to deliver content to the visitor within his/her region.

Let’s suppose you live in Canada and want to visit any asian region website. In this case your requests will be handled from local canadian PoP servers which has cache version of the required website.

Why CDN is Necessary?

CDN ensures speedy delivery of content, thus improving the speed of websites and web apps. When a CDN is active, the actual location of the website does not matter. The CDN ensures that the visitor receives the data from the nearest location. Since many frameworks are well known for powering fintech and ecommerce applications, CDn plays a central role in speeding up the user experience.

CDN helps website in so many ways like:

  • Saving the website/applications from DDos attack
  • Handle Traffic spikes smoothly by distributing visitors
  • Maintaining Load balance between multiple servers.
  • Localizing the coverage of your site without more cost.
  • Improve the page load speed.
  • Implementing CDN in Websites

To implement CDN, your website must be deployed on live server. Here I will use Cloudways PHP PaaS. And configure stackpath CDN on my server. Since you don’t need to buy CDN externally and configure it in your application because you can directly move to the platform and enable Cloudways CDN with a click.

When you login to your server, move to the Application tab and open the PHP application. You will see the tab for configuring CDN at the end of the options. When you click the tab, you will enter the CDN configuration screen. Here you will find the URL of the application to be inserted in the WEBSITE URL field and click the Create button.

image7.png

Next you will get the newly generated URL for your website/application:

image2.png

Few things to note here:

  • You can view the bandwidth usage on this screen.
  • You can always purge old content from CDN by using the Purge button.
  • You can always remove your subscription anytime.

Integrate Cloudways CDN in PHP Frameworks

Now that you got the CDN url let’s integrate this in PHP and PHP framework applications simultaneously.

Symfony

Symfony provides easy configuration options for CDN services. If you know about base_url, you are good to go. In the standard Symfony installation, move to app >> config and open config.yml.

You need to find the asset settings in framework configs. Since our CDN is asset based, I will concatenate on the CDN Url as base_url to every asset file in Symfony.

framework:
  assets:
      base_urls:
          - 'https://3971-7889-2-raikfcquaxqncofqfm.stackpathdns.com/'

Now clear your cache by running rm -fr var/cache/* and check your Symfony application asset URLs:

image1.png

If you are using Symfony Flex for application management, then in your project folder, move to config >> packages folder and open framework.yaml file. Add the same asset config as shown above.

Codeigniter

In Codeigniter you need to extend the existing cdn_base_url function by overwriting it.

For this, start by creating the file: application/helpers/cdn_helper.php

function cdn_base_url($uri)

{
   $currentInstance =& get_instance();
   $keybasedcdnUrl = $currentInstance->config->item('cdn_based_key_url');
   $extensions = array('css', 'js', 'jpg', 'jpeg', 'png', 'gif','pdf');
   $pathParts = pathinfo($uri);

   if (!empty($keybasedcdnUrl) && in_array($pathParts['extension'],$extensions)) {
       return $keybasedcdnUrl . $uri;
   }

   return $currentInstance->config->cdn_base_url($uri);
}

function cdn_base_url($uri)
 
{
   $currentInstance =& get_instance();
   $keybasedcdnUrl = $currentInstance->config->item('cdn_based_key_url');
   $extensions = array('css', 'js', 'jpg', 'jpeg', 'png', 'gif','pdf');
   $pathParts = pathinfo($uri);
 
   if (!empty($keybasedcdnUrl) && in_array($pathParts['extension'],$extensions)) {
       return $keybasedcdnUrl . $uri;
   }

   return $currentInstance->config->cdn_base_url($uri);
}

This code will overwrite the cdn_base_url function to support and load the website assets from loading your asset from the key based CDN.

The next step is setting up the CDN URL. For this, you need to modify this file: applicaiton/config/config.php. Add the following line into the file . Remember to replace the cdn based url with the proper URL:

$config['cdn_based_key_url'] = 'cdn based url';

Here is the output in action:

image8.png

Yii2

In Yii2, you first need to install the CDN library using composer. Run the following command to install it:

php composer.phar require --prefer-dist blacksmoke26/yii2cdn "*"

Now at your root folder create a folder called cdn. Now in cdn folder create another folder called css and put your css files like style.css in it. Now open the web.php file from app/config/web.php and add the following code in components section:

// ...
'components' => [
    // ...
    'cdn' => [
        'class' => '\yii2cdn\Cdn',
        'baseUrl' => '/cdn',
        'basePath' => dirname(dirname(__DIR__)) . '/cdn',
        'components' => [
            'style' => [
                'css' => [
                    [
                        'css/style.css', // offline
                        '@cdn' => 'https://3971-7889-2-raikfcquaxqncofqfm.stackpathdns.com/css/style.css', // online version
                    ]
                ]
            ]
        ],
    ],
  // ...
],
// …

Now in view file add the following code:

Yii::$app->cdn->get('style')->register();

Now check your HTML in browser to assure the url has been replaced with CDN urls.

CDN Benchmarking with Images

In the CDN benchmarking, I downloaded three image files (Small: 78.6KB, Medium: 747KB, Large: 1.28MB) for 3.5 hours with 5 minutes intervals. These files are taken from a WordPress site hosted on Cloudways. the tool we used is an open-source Node.js CDN benchmark CLI.

The comparison benchmark has been done with three CDN providers:

  • CloudwaysCDN (Partnered with StackPath formerly known as MaxCDN)
  • CloudFlare
  • KeyCDN

Let’s see what results are generated by the test.

Small Image

image4.png

Medium Image

image3.png

Large Image

image6.png

The graphs are pretty much self defined. You can see the performance of three CDN providers let’s summarize the above results in to one graph:

image5.png

The results from the above graph are pretty straightforward. CloudwaysCDN had the highest downloading speed in all three categories of files. KeyCDN came second with average score. CloudFlare got third position with lowest score due to huge spikes in the initial stages of all three tests. It performed pretty well in the midst and end of the tests.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

@shahroznawaz, I gave you an upvote on your first post! Please give me a follow and I will give you a follow in return!

Please also take a moment to read this post regarding bad behavior on Steemit.