Welcome Guest, Not a member yet? Register   Sign In
multiple sites, 1 codebase, using symlinks (with smarty)
#1

[eluser]CodeOfficer[/eluser]
Greetings all,

First, I'd like to say thanks for making a great framework, its flexible and fun to use! I've only been at it a few days but am very impressed. I even managed to get Smarty templates integrated with very little trouble. (not required I know but was my preference)

Now onto the meat ...

MY REQUIREMENTS

My project called for a specific configuration of sites and applications:

Code:
site #1: one application
site #2: has both frontend and backend applications
     (will also operate on wildcard sub-domains)
site #3: uses ssl with one application
site #4: one application (internal access)

All 4 sites are heavily related ... and will often want to use the same models, libraries, helpers, views etc. Unfortunately CI doesn't give me a place to store these resources cross-application, and I really didn't feel comfortable editing or extending the core CI classes. That might have made upgrading the framework painful with later releases. I like the idea of just 'dropping in' a new system folder without worry.

MY HOMEWORK (B-)

So as I was looking into CI initially, I found a lot of posts about running multiple-application sites. Overall, I got the impression that this was something CI 'could' do with tweaking (depending on your specific sites/applications) but wasn't particularly great at out of the box. Thankfully, CI is so easy to work with that there are a number of solutions to consider.

Option 1:

One alternative was to run all my apps out of the same application folder, and just give them unique controllers ... I considered this but thought it might be difficult to keep site #1 from calling site #2's controllers by editing the urls. My sites needed to be fairly secure in this regard.

Option 2:

Another alternative was to modify the loader of the CI core classes to include a new search path, essentially adding a Library level where cross-application code goes. This would have been the most attractive option if I felt more comfortable editing core files. But I don't ... ick! Hopefully CI adopts a similar solution officially in a later release.

Some related links on that method:

http://www.jaaulde.com/test_bed/CodeIgniter/modLoader/
http://ellislab.com/forums/viewthread/49157/

And other options I won't get into right now ...

MY BACKGROUND INFO

My situation is unique to me perhaps. I happen to own the box my sites are being hosted on, so all configuration options are available. My sites use the traditional php5, mysql5, apache2 on Free(as in beer)BSD. I can edit httpd.conf freely and create .htaccess files as needed.

MY SOLUTION

I found I was able to share a (parent) application folder (located outside each site's root) with a specific site's (local) application folder ... I did this by creating a series of symbolic links in each (local) application folder to represent the corresponding folders in my (parent) application folder ...

I literally matched symbolic links to parent folders exactly ... EXCEPT for the (local) application's 'controllers' folder, which was really the meat of each website.

It might be easier to show you the following folder hierarchy I used:
Code:
application/
    my global application folder, where most the code goes
CodeIgniter_1.5.4/
    my CI installs system folder and other files, I leave the version
    number so that I can link to a new system in the index.php if
    needed for testing
common/
    an apache directory alias called common lets me link to subfolders here
    called img, js, css, file, etc. Having one folder with all my includes makes
    it easy to specify in an .htaccess file that CI should leave links alone with
    the word common in it.
Smarty_2.6.18/
    my smarty install, contains the actual libraries
www_site1/
    the site root for site #1
www_site2/
    the site root for site #2
www_site3/
    the site root for site #3
www_site4/
    the site root for site #4
#2

[eluser]CodeOfficer[/eluser]
A closer look at my (GLOBAL) application folder:

Code:
cache
    SMARTY SPECIFIC FOLDER with write access
config
    standard codeigniter
configs
    SMARTY SPECIFIC FOLDER
controllers
    NOT USED GLOBALLY - EACH SITE HAS ITS LOCAL CONTROLLERS FOLDER
    FOLDER IS ACTUALLY EMPTY
errors
    standard codeigniter
helpers
    standard codeigniter
hooks
    standard codeigniter
libraries
    contains a wrapper class called MySmarty.php for smarty useage
models
    standard codeigniter
templates
    SMARTY SPECIFIC FOLDER
templates_c
    SMARTY SPECIFIC FOLDER with write access
views
    standard codeigniter

A closer look at my (LOCAL) application folders (EACH SITE HAS ITS OWN):

Code:
cache
    symbolic link to parent
config
    symbolic link to parent
configs
    symbolic link to parent
controllers
    ALL LOCAL SITE SPECIFIC CONTROLLERS GO HERE
    default controller is index.php as set in CI's global config
errors
    symbolic link to parent
helpers
    symbolic link to parent
hooks
    symbolic link to parent
libraries
    symbolic link to parent
models
    symbolic link to parent
templates
    symbolic link to parent
templates_c
    symbolic link to parent
views
    symbolic link to parent

A closer look at my individual site's ROOT folders

Code:
.htaccess
    (see below)
index.php
    links to (local) application folder and global system folder
    system folder can be changed in one place to reference a new CI install
applications
    mostly contains symbolic links, but has a legit controllers folder

A closer look at my sites individual .htaccess files:

Code:
Options +SymLinksIfOwnerMatch
    
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond $1 !^(index\.php|common|robots\.txt)
    RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>


TWEAKAGE:

A few small edits I made along the way.

For SSL.

Since I have a single CI config file for multiple applications/sites I had to make a small change to the way the $config[base_url] was captured. It now prefixes the URL with the proper protocol if SSL is in use on that site.

Code:
$config['base_url']    = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://').$_SERVER['HTTP_HOST']."/";

instead of

Code:
$config['base_url']    = "http://".$_SERVER['HTTP_HOST']."/";

For Smarty.

In my (global) applications autoload.php file, I add the following:

Code:
$autoload['libraries'] = array('mySmarty');

Then I create a class file in my (global) application/libraries folder (remember to edit the smarty path)

Found on the CI forums, thx to the author whoever you are!

Code:
if (!defined('APPPATH')) exit('No direct script access allowed');

require_once(APPPATH . "../../Smarty_2.6.18/libs/Smarty.class.php");

/*
|==========================================================
| Code Igniter - by pMachine
|----------------------------------------------------------
| www.codeignitor.com
|----------------------------------------------------------
| Copyright (c) 2006, pMachine, Inc.
|----------------------------------------------------------
| This library is licensed under an open source agreement:
| www.codeignitor.com/docs/license.html
|----------------------------------------------------------
| File: libraries/Smarty.php
|----------------------------------------------------------
| Purpose: Wrapper for Smarty Templates
|==========================================================
*/

class MySmarty extends Smarty{

    var $smarty;
    
    function MySmarty()
    {
        $this->smarty = new Smarty();
        $this->smarty->template_dir = APPPATH . "templates";
        $this->smarty->compile_dir = APPPATH . "templates_c";
        $this->smarty->cache_dir = APPPATH . "cache";
        $this->smarty->config_dir = APPPATH . "configs";
        $this->smarty->compile_check = true;
        $this->smarty->debugging = true;
        log_message('debug', "Smarty Class Initialized");
    }
    
    function assign($key,$value)
    {
        $this->smarty->assign($key,$value);
    }
    
    function display($template)
    {
        $this->smarty->display($template);
    }

}

I hope this is helpful for some, I appreciated having the forums as a resource to gather information from. CodeIgniter has a great community here.

Peace. Smile
#3

[eluser]openology[/eluser]
Hi
I use smarty too for template and I like to learn how people are with it and dealing with situations that is covered by standard CI but probably have to handle separately when using with Smarty.
An example is form.

BTW,why do you need to re-declare assign and display but not adding anything extra? since the class extends smarty it should be available directly. Am I missing something?
#4

[eluser]CodeOfficer[/eluser]
[quote author="openology" date="1186135242"]Hi
I use smarty too for template and I like to learn how people are with it and dealing with situations that is covered by standard CI but probably have to handle separately when using with Smarty.
An example is form.

BTW,why do you need to re-declare assign and display but not adding anything extra? since the class extends smarty it should be available directly. Am I missing something?[/quote]

Well, I prefer to autoload my smarty wrapper as i have completely replaced CI's view engine with it.

In your controller, you can load your variables into smarty as such:
Code:
$this->mysmarty->assign('sports', array(
    '10' => 'Baseball',
    '20' => 'Soccer',
    '30' => 'Football'));
and then call something like:
Code:
$this->mysmarty->display('template.tpl');
#5

[eluser]HdotNET[/eluser]
fyi, trying something similar myself... found the logging messages a bit difficult as they all get dumped into the same log file no matter what site you are looking at.

Therefore I took the Log.php library and made a simple edit around line 92:

from
Code:
$filepath = $this->log_path.'log-'.date('Y-m-d').EXT;

to
Code:
$filepath = $this->log_path.$_SERVER['HTTP_HOST'].'-log-'.date('Y-m-d').EXT;

EDIT: typo on log.php.. DOH!
#6

[eluser]CodeOfficer[/eluser]
Oooo nice idea. I'm going to use that Smile Thanks.
#7

[eluser]E1M2[/eluser]
I've been going through the forum checking best strategies for multi app executions and I must say, this is a sweet setup.
I've set everything up as outlined (dir structure, symlinks etc.) but I do have a few potential differences:

INDEX.PHP
My local installation is housed at 'http://192.168.0.3/webapp' with a path of '/htdocs/webapp'
Here is how I've setup my application switch. Notice I am using the URI to then go to the approriate app directory.

Code:
$myApp = '';
$uriArr = explode("/", $_SERVER['REQUEST_URI']);

switch($uriArr[2])
{
    case 'cms':
        $myApp = 'www_cms';
        break;

    case 'id':
        $myApp = 'www_id';
        break;

    case 'test':
        $myApp = 'application';
        break;

    default:
        $myApp = 'application';
    }
    
$application_folder = $myApp;


PROBLEM
Issue is, whenever I then go to http://192.168.0.3/webapp/cms -OR- http://192.168.0.3/webapp/id even http://192.168.0.3/webapp/test I get a 404. http://192.168.0.3/webapp/ works fine.

I have not changed anything with the application constants in INDEX.PHP and my .htaccess (/htdocs/webapp) is as follows:

Code:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /webapp
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>

.htaccess in my app folders (www_cms, www_id)

Code:
Options +FollowSymLinks



CLOSING
I'm wondering if there is a step I'm missing. Possibly with the .htaccess in /webapp -OR- the index.php file itself. What are your thoughts?
#8

[eluser]E1M2[/eluser]
SOLVED

The setup for multi sites using 1 codebase and symlinks works as is on the live server. I have my sub domains (cms.domain.com, id.domain.com) mirrored to the main domain.com. No files are being copied here it's directly linked.

CHANGES IN INDEX.PHP (REMOTE SERVER - DOMAIN.COM)

Code:
// System folder var
$system_folder = "system_1.5.4";


// Application folder var
$myApp = '';

switch($_SERVER['HTTP_POST'])
{
    case 'cms.domain.com':
        $myApp = 'www_cms';
        break;

    case 'id.domain.com':
        $myApp = 'www_id';
        break;

    default:
        $myApp = 'application';
    }
    
$application_folder = $myApp;


// Application Constants
//Commented out the whole if(is_dir($application_folder)) biz and changed the APPPATH so I have just have the following:

define('EXT', '.'.pathinfo(__FILE__, PATHINFO_EXTENSION));
define('FCPATH', __FILE__);
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
define('BASEPATH', $system_folder.'/');
define('APPPATH', realpath($application_folder).'/');



FOR LOCAL SERVER
Had problems due to my use of the REQUEST_URI in order to do a switch for my $application_var locally. My work around for this is simple (...maybe not the best).

Instead of depending on '/htdocs/webapp/' (http://192.168.0.3/webapp/) index.php file
to filter out the REQUEST_URI and switch the application_folder var. I placed separate index.php files in '/htdocs/webapp/www_cms' and '/htdocs/webapp/www_id'. Instead of trying to access by pointing the brower to http://192.168.0.3/webapp/cms etc., I now access them directly (http://192.168.0.3/webapp/www_cms -OR- http://192.168.0.3/webapp/www_id)

LOCAL INDEX.PHP USED

Code:
// System folder var
$system_folder = "../system_1.5.4";

// Application folder var
$application_folder = '../www_cms'; -OR- $application_folder = '../www_id';

// Application constant
define('APPPATH', realpath($application_folder).'/');
#9

[eluser]CodeOfficer[/eluser]
E1M2, Your solution for local server is exactly what I did on my live servers, separate index files and .htaccess files ... I liked having more granular control via separate master controller files. Glad this was of use to you, I'v been using the approach for a few months now and no issues.

For each of my 4 webroots i have the following structure:

Code:
.htaccess
application/
favicon.ico
index.php
robots.txt
#10

[eluser]Pygon[/eluser]
Just a note -- your Smarty loader isn't of the best design.

Code:
class MySmarty extends Smarty{

    var $smarty;
    
    function MySmarty()
    {
        $this->smarty = new Smarty();
        $this->smarty->template_dir = APPPATH . "templates";
        $this->smarty->compile_dir = APPPATH . "templates_c";
        $this->smarty->cache_dir = APPPATH . "cache";
        $this->smarty->config_dir = APPPATH . "configs";
        $this->smarty->compile_check = true;
        $this->smarty->debugging = true;
        log_message('debug', "Smarty Class Initialized");
    }
    
    function assign($key,$value)
    {
        $this->smarty->assign($key,$value);
    }
    
    function display($template)
    {
        $this->smarty->display($template);
    }

}

Note that when you call load->module("MySmarty"), you are effectively creating a new object of MySmarty class, which is also creating a new object of Smarty class, which is already extended by MySmarty.

Effectively you are creating two instances of Smarty each time you load MySmarty -- $this->MySmarty->cache_dir and $this->MySmarty->Smarty->cache_dir exist but are different values.

I would assume that the intention was to create one object (not having the ability to create multiple smarty objects).

This is what I use, based on some code I've run into and my own design:
Code:
class MySmarty extends Smarty {
    
    function MySmarty(){
        $this->Smarty();
        
        $config =& get_config();
        
        $this->template_dir = ! empty($config['smarty_template_dir']) ? $config['smarty_template_dir'] : BASEPATH."application/views/smarty/templates";
        $this->compile_dir = ! empty($config['smarty_compile_dir']) ? $config['smarty_compile_dir'] : BASEPATH."application/views/smarty/templates_c";
        $this->cache_dir = ! empty($config['smarty_cache_dir']) ? $config['smarty_cache_dir'] : BASEPATH."application/views/smarty/cache";
        $this->config_dir = ! empty($config['smarty_config_dir']) ? $config['smarty_config_dir'] : BASEPATH."application/views/smarty/config";
        
        //Eliminates URL Helper requirement
        $CI =& get_instance();
        $site_url = $CI->config->slash_item('base_url');

        $this->assign("site_url",$site_url);
    }

}

Load smarty as normal:
$this->load->module("MySmarty");
Use it as normal:
$this->MySmarty->assign() -- etc.

Enjoy the reduction of memory usage per script.




Theme © iAndrew 2016 - Forum software by © MyBB