How to automatize the Bootstrap installation in Codeigniter or any Php project using Composer

Published Apr 06, 2018
How to automatize the Bootstrap installation in Codeigniter or any Php project using Composer

Composer is a great tool to manage your packages dependencies but it sucks when the package is a frontend framework like Bootstrap.

Why?

With usual packages that include php classes etc. we just run a composer require and your autoloader will complete the magic. But when is about Bootstrap, the things are more complicated. The autoload works with Php classes and not with bunch of css and js files. To complicate more the situation is the need to have this css and js files in public folders accessible externally.
The usual, bad, solution to the problem is to download manually Bootstrap and to put it in the public folder.

So being lazy, I tought a really easy and fast solution to the problem (in this case related to Codeigniter but easily adaptable to other contexts):

Include your Bootstrap with Composer:

composer require twbs/bootstrap

Here come the magic, let's create a post-package-install event in Composer that fires when Bootstrap has been installed:

"scripts": {
        "post-package-install": [
            "vendor/twbs::postPackageInstall",
            "mkdir ./assets",
            "ln -s ../vendor/twbs/bootstrap/dist/js  ./assets/js",
            "ln -s ../vendor/twbs/bootstrap/dist/css  ./assets/css"
        ]
    }

As you can see, after the Bootstrap package installation, the script create an assets folder and inside it, two soft link related to Bootstrap vendor folder.

And that's it!

Now you can just insert your reference in the index file:

<link href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" rel="stylesheet">

<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script>

and you are ready to go!

Discover and read more posts from Stefano Maglione
get started