Welcome Guest, Not a member yet? Register   Sign In
How to have shared libraries and helpers between applications in CodeIgniter 3
#1

Assume the following situation:

- 2 applications using 1 CodeIgniter installation under the same URL
- The requirement to share libraries and helpers (and maybe more) between application
- and...reduce redundant code

PS. change the server names below to your own situation!

Code:
- CodeIgniter-3.1.10 <- framework, don't change anything here
 - ....
- server <- 1. server
 - application
   - ...
- server_other <- 2. server
 - application
   - ....
- server_common <- package with the shared code
 - libraries
 - helpers

How to do it?

In the index.php of both servers (not the common one):

Code:
// $system_path = "system";
$system_path = dirname( __FILE__, 2 ) . '/CodeIgniter-3.1.10/system';

In the autoload.php of both servers you add the following:

Code:
$autoload['packages'] = [dirname(__FILE__, 4) .'/server_common'];
$autoload['libraries'] = [...];
$autoload['drivers'] = [... ];
....

Sample of a common library "Itworks.php" in folder "libraries" of "server_common":
Code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Itworks
{
   function show()
   {
       echo 'it works great';
   }
}

Sample of a controller calling the "show" function in either of the other servers:
Code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Valhalla extends CI_Controller
{
   public function __construct()
   {
       parent::__construct();

       $this->load->library('itworks');
   }

   public function itworks() {
       echo $this->itworks->show();
   }
}

As you can see, once loaded it works like a normal library.
And, you can still load the local libraries on the server too.

Now use in your browser:
Code:
https://www.yourserver.com/server_other/valhalla/itworks
showing: 'It works great'
Reply




Theme © iAndrew 2016 - Forum software by © MyBB