I'm building a codeigniter application that will serve custom microsites. Essentially each microsite will be a collection of seven different views all loaded by a single controller's methods. To 'Theme' each microsite there will be different folders containing different versions of these view files (and their associated css, js and image files) and the controller will know which folder of views to load based on information stored in the database for each microsite record.
The problem with this approach is when a single microsite needs to have a custom page that is unique from all the other microsites. Since they're all controlled by one controller, we run into the limitation that either all the microsites need to support this page.
To futher explain what I'm referring to imagine these urls:
http://www.fakewebsite.com/index.php/microsite/index/david_site
http://www.fakewebsite.com/index.php/microsite/index/frank_site
In both of these links the controller is 'microsite' and the method is 'index'
'index' knows what template to return based off it's first argument which is either 'david_site' or 'frank_site' in the above example.
I can't say if this is possible with Codeigniter, but I assume so:
So what's now your problem? That you have too much code in the controllers? Move code from the controllers into the models. Then the code is more re-useable and you can have small controllers on each microsite with fat models that are shared anyway.
Sounds not really good so far, right? Still there's one controller per each site. Well, make each microsite's controller extend from a base controller. So all code's still in one place but for some controller methods they can extend that base controller on a per-site basis.
So the front-end controller then will provide the right controller class per site as it does for the themes - if I understood your question right.
Can you have a default "theme" for that controller, which would accommodate most of your microsites, and then if you need to create custom themes on top you can change it?
So like this
http://www.fakewebsite.com/microsite/david_site/ <-- default theme
http://www.fakewebsite.com/microsite/frank_site/ <-- default theme
http://www.fakewebsite.com/microsite/john_site/customtheme/ <-- custom theme
As I understand the question, you're asking how to load a different view file for only specific "microsites", but you're using the same controller and codebase for all of them.
In your views directory, have 1 directory for default themes, and and then for each "microsite" you want to do something custom with, create another directory which will contain the unique files, then when loading files - check if the unique exists first.
Hasty example that assumes default files are in the root of views/:
// I assume we know which site we're loading
$theme = 'david_site';
// Whatever the current view's name should be
$view = 'page3';
// Path to our custom file if it exists
$custom = APPPATH.'views/'.$theme.'/'.$view;
// Does a custom view exist?
if (file_exists($custom))
{
$view_file = $theme.'/'.$view;
}
else
{
// Use the default
$view_file = $view;
}
$this->load->view($view_file);
As far as I know, there's nothing like view_file_exists() in CI, so we're just using plain old file_exists() with the full path.
It would be worth writing a function for this of course, but hopefully this helps. You could even apply it to loading libraries, models, etc. - or even extend the Loader class to do it automatically (probably overkill).
CI2 already has a version of this feature in the ENVIRONMENT constant, although this usage is not its intention - but that is basically what it does.
Related
I would like to use Kohana 3.3 as a replacement for my self written "framework" which I am currently using for my webapp. Could you please tell me if it is possible to fulfill the following requirements and how to achieve this?
My app consists of several controllers, which I want to access via menu. This menu should be dynamically created, so that a newly created controller will show up immediately. Additionally the menu should exclude controllers which are not accessible for the currently logged in user.
Each controller must be able to check the user's role before executing an action (e.g. global admin, controller-specific admin, regular user). Depending on this role each controller must be able to permit or prohibit access. (Thought about a group membership based method).
I want to use a separate template (as far as I know aka partial) for the menu and for each controller output. They all should be merged with a "frame" template (with header, footer,login info, etc.). I saw there is a special controller for templates (template_controller iirc) - is this the right one to use as my base controller? And should I create a base controller which manages my "template" and nest the other controllers in it somehow?!
Additionally it would be nice if each controller had the ability to recognize the current request as ajax or non-ajax and adjust the rendering accordingly (in most cases "rendering" the whole site again is not desired with ajax).
I would be grateful for every answer!
Thanks in advance.
Yes, but you'd have to search for the controller files yourself AFAIK.
Yes, see before(),
2.1 If you want to keep it in one place you would only have to write a little extra something to specifiy which action requires what privileges. Check out Kohana's Request class for some nice stuff you could use for this (I'd say take a look at the url, uri and request methods, I don't know by hard what exactly they do)
2.2 You could also do it on a per-controller basis; e.g. Controller_Admin could do the following ugly one-liner (check snippet for 2.2 below). I suggest splitting it up a little bit though, e.g. giving your base controller a protected $_user variable which it fills in it's before() method and then use $this->_user instead of Auth stuff.
It's Controller_Template but yes, you got that right ;)
Like this? Request::$current->is_ajax() (http://kohanaframework.org/3.3/guide-api/Request#is_ajax)
Snippet for 2.2:
if ( ! Auth::instance()->get_user()->has('role', ORM::factory('Role', array('name' => 'admin')))
throw new HTTP_Exception_403('Permission denied!');
Really not sure if the title of the question suits the question overall. But here goes.
What I have currently is an existing SaaS project. That we want to roll out a new template over time. Think of how google introduces new features. Or some other sites might with "Try our new Beta Version".. type of thing. Well we want to do the same, and then we will eventually phase out the old look and feel.
With that, this application is built on top of Zend Framework, so looking through docs I can figure out how to override the template on a given controller. But what I want to basically do, is likely going to make use of the sessions. If it exists, use this template. If not, use the old one.
Is it possible to override the default template in such a fashion? Right now for example, the default loaded file, is "tops.phtml" if the session exists I'd like to load "tops_v2.phtml" for example. So it can use that as the template instead of "tops.phtml" when the session is found.
Zend Framework 1.x solution:
You can disable ViewRenderer plugin in the action, and choose template manually:
public function indexAction(){
$this->_helper->viewRenderer->setNoRender(true);
echo $this->view->render("path/to/template/template.phtml");
}
I think that layouts are the thing you probably want to use, as was briefly touched on by Richie. Based on the question, I'm guessing you aren't already using them. Ultimately you can design a layout that defines the overall website look and then each of your action templates will only then render a fragment of the page (which will be dynamically placed in the content portion of the layout).
Using whatever logic you choose, you can then assign one of any number of layouts to be used on a given page load and of course you could store this as a user preference or something.
CI looks for Segment[1] for controller (in controller dir) and Segment[2] for Method. Now, I have specific requirement by business application which needs that I do not want CI to look or by force go to controller dir to load but I will have something like this "domainURL/module_identifier_id/controller/method/".
Here, every request will be coming along with its associated Module's Identifier ID which will have complete module's configuration and other data (controller files, module location where it was uploaded, all menus and their URLs which will have same URL mechanism which we want to design for developers to develop modules and upload) stored in DB.
We need to get this ID and play with it to fetch relevent records and point CI to load controller from where we want it and indeed rest for methods etc every thing needs to be working as it is.
I hope you understand what we are looking for that we have our own main controller type file where all of the requests will be coming with customizing protocol as described above and developers will be following it by all means, that there must be module identifier first and then controller, method etc...
Let me know if you have any query to be cleared on?
I think I would just use routes for this:
$route[(:any)/(:any)/(:any)] = '$2/$3/$1';
This should just rearrange your segments the way you want, without completely changing the way the native routing system works.
I have an object oriented framework that uses a page design, where each page extends a view of the framework. So, for instance, my index page for a site is actually a class that implements the abstract class View provided by the framework. I hook the framework by including a startup script at the top of the page and after some processing the framework creates an instance of the page and processes its view data. To add flexibility to the system, I don't require the class name to be the name of the file itself. This allows me to create something like a support class and have it behave as the index for the /support/ subdomain.
I was initially passing the page's class name into the framework via the framework's constructor, but this added a few more steps to the top or bottom of the page. I currently obtain the class name via a pages table in the database identified by a filtered requested URI. I use this table to build navigation and adding an extra table column was practically free. This works OK as long as I have a database connection, but I'm trying to implement static page support for status messages and error reporting, and I need another method for creating an instance of the page's class. If I use the standard convention of naming the class the file's name, then I know I have a dependable way of extrapolating the class name. I don't really want to name all my classes index just for presentation reasons. What is some advice or some standards for how object oriented frameworks are initialized?
View.inc
<?php
abstract class View
{
abstract function getView();
}
?>
Startup.inc
<?php
require_once("View.inc");
require_once("CoreController.inc");
$Framework = new CoreController();
$Framework->Initialize();
exit;
?>
index.php
<?php
require_once("Startup.inc");
class Index extends View
{
public function getView()
{
echo "<pre>View Data</pre>";
}
}
?>
Within my framework I have a TemplateController that processes the page. The page class is known because it is mapped via another class. Without a database however, I would like to discover the class within, say, index.php without changing the way it's currently set up. Here is the actual code within the TemplateController.
//Get the View Class from Page
$view = $page->getPageClass();
//We need to catch View creation failure
$this->Page = new $view($this->Framework);
//Initialize the Page View
$this->Page->Initialize();
//Cache the Page View
$this->cacheView($this->Page, $page->getPageName(), $this->SiteID.TCS_PAGE_SORTID);
In the snippet above $view is the actual name of the class that was mapped from another controller. I'm passing a reference to the framework to the view's constructor and the rest is really irrelevant. I'm trying to come up with a similar mapping technique to identify the page class in the event the database is down. I like the one include line for the framework startup and would like to keep it that simple.
At the top of the TemplateController I have to also reinclude the actual page, since my startup script is at the top, the actual class is not included even though it is the requested page.
include($_SERVER['SCRIPT_FILENAME']);
Please review Stack Overflow question Identifying class names from $_SERVER['SCRIPT_FILENAME'] for more information on what I'm attempting to do.
Here is my checklist of page routing:
Adding new page must be quick
You must not be able to add page unintentionally
Application with million pages should not be slower or more bloated than application with 2 pages
Provide simple way and let people enhance it if they want
Allow easy re-factoring, such as moving several pages into different location
Make framework detect everything. Don't force user to specify base URL, etc.
Create simple to understand page names (hello/world).
Clean illegal characters from the URL
Make it possible to add static pages easy
Provide a way to generate URLs from page names.
Allow user to use pretty URLs by changing what appears before and after the page in the URL
And most importantly
- Stop copying, think about the best approach.
All of those suggestions I have used in the PHP UI framework - Agile Toolkit where I am a contributor.
Relevant sources: Agile Toolkit - a PHP Framework with jQuery, Agile Toolkit - PageManager.php, Agile Toolkit - URL.php and Agile Toolkit - PathFinder.php.
We wanted to make it really simple for developers. And secure too. And flexible. Therefore the "page" class is selected based on the URL. How? Quite easy:
/hello.html -> page_hello
/hello/world.html -> page_hello_world
Class then is mapped into filename. page/hello/world.php
Then there are cases when we want to use dynamic URLs too, such as: /article/234
Many frameworks implement a complex techniques here (arrays, regular expressions, front-controllers). We don't. There is mod_rewrite for this. Just rewrite this into page=article&id=234 and it works. And scales.
Apart from pages, there are other classes, but those classes can't be accessed directly. Therefore pages live under the /page/ folder, do distinguish them and maintain security.
Then comes the designer saying - "I won't write PHP". So we introduce static pages. If class page_hello_world is not defined, we'll look into template/skin/page/hello/world.html. That's a easy shortcut for designers and non-developers to add a new page.
What if a page is not found? Api->pageNotFound() is called. Feel free to redefine and load pages from SQL or display 404 page with a picture of a pink elephant.
And then there are some pages which come from add-ons. We don't want to enable them by default, but instead let users add them to their app somewhere. How?
class page_hello_world extends Page_MegaPage
Next question, is how we handle sub-pages of that page, since sometimes all the functionality can't fit on single page. Well, let's add support for page_edit() method (or any page_XX) as an alias for a sub-page inside those classes. Now add-on developer can include a multifunctional page which can be extended, customized and placed anywhere in the application.
Finally there are hackers, who want to do something really fast. For them we apply same technique to the API. You can define function page_hello_world in the API, and you don't need class.
Some might say that there are too many ways to do a simple thing. Oh well.
I hope that this was helpful.
Use __autoload(). Most major PHP frameworks use autoloading to streamline class loading.
You need some way to map a URL to an object, which is usually handled by a routing component in most frameworks. Might want to take a look at libraries such as https://github.com/chriso/klein.php, or the routing components of the major Frameworks out there (Zend, Symfony, etc.).
Why not to use information from URL to detect correct class? Since you won't use database for static pages, you have to somehow store mapping between URL and class in file. I.e. you will have a file mapping.php:
return array(
'about' => 'AboutView',
'copyright' => 'CopyrightView',
);
Here, about and copyright are URL components and values represent appropriate child classes of View. You can have URL's like http://example.com/index.php?page=about and use rewriting capabilities of webserver to make them look good.
You will change implementation of Page::getPageClass() in order to return correct view class. Depending on URL it will use static mappings from the file above or use database.
What's the problem with this approach?
What class(FrontController , Bootstrap, Dispacher....) sets up the default structure path in ZF?
There is no single instance that has all the paths. Each component has it's own defaults, e.g. the FrontController knows that the controller directory should be named controllers, but it doesn't know how to make a full path from it (Dispatcher does it) or where to find the Action Helpers. That's defined in ActionHelper Broker. Consequently, Zend_View_Abstract holds the paths for View filters, helpers and scripts, etc.
Like #Pascal mentioned in his comment, you should not modify ZF at it's core. You will lose the changes once you update to a newer version anyway. Configure the paths through the API in your bootstrap or through the application.ini instead.
Actually it's the dispatcher's job to find the requested action controller.
So you'll have to extend either Zend_Controller_Dispatcher_Abstract or Zend_Controller_Dispatcher_Standard or even create a completely new one based on Zend_Controller_Dispatcher_Interface to fit your requirements.
But be aware that you'll have to change the way Zend_Controller_Action_Helper_ViewRenderer tries to find the required view files, too.