how to auto load mobile templates by agent in codeigniter? - php

dir:
application
-controllers
-models
-views
-mobile_views
How do I auto load templates at mobile_views when I use $this->load->view and view by iphone or other mobile phone?

Check this
You can do it in two way.
Way 1: Its very simple. In the above answer (the link I have given) add following line in the end of MyController function
$this->load->_ci_view_path . = $this->view_type .'/';
You are done. You can simply load view like normal view load.
Way 2:
To autoload a view based on user agent, I think you can implement it using hooks. To implement this hooks you need to follow the following steps
Autoload user agent library in autoload.php
$autoload['libraries'] = array('user_agent');
Enable hooks in config.php
$config['enable_hooks'] = TRUE;
Not implement hooks on post_controller_constructor. Add following codes to hooks.php
$hook['post_controller_constructor'][] = array('class' => 'Loadview',
'function' => 'load',
'filename' => 'loadview.php',
'filepath' => 'hooks'
);
Now create a page named loadview.php under hooks directory having following code
class Loadview
{
public static $MOBILE_PLATFORM = 'mobile';
public static $DEFAULT_PLATFORM = 'default';
public function load(){
$this->CI =& get_instance();
$view_type = $this->CI->agent->is_mobile() ? self::$MOBILE_PLATFORM : self::$DEFAULT_PLATFORM;
$this->CI->load->_ci_view_path = $this->CI->load->_ci_view_path . $view_type .'/';
}
}
You are done now. You can simply load view like normal view load.

to load views from another dir aside from "views", i found this forum topic to be helpful
http://codeigniter.com/forums/viewthread/132960/
function external_view($path, $view, $vars = array(), $return = FALSE)
{
$full_path = $path.$view.'.php';
if (file_exists($full_path))
{
return $this->_ci_load(array('_ci_path' => $full_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
else
{
show_error('Unable to load the requested module template file: '.$view);
}
}
and you can work the rest from the controller.

I do this in my controller:
public function index()
{
if($this->agent->is_mobile())
{
$this->load_mobile();
}
else
{
$this->load_web();
}
}
public function load_mobile()
{
$this->load->view('mobile/home');
}
public function load_web()
{
$this->load->view('web/home');
}
In this way I can add different data to mobile and to web pages.
I also extend the default controller and add some useful extra features:
Enables the usage of master page/templates.
Can add css and javascript files.
Uses the _output method for controlling the controllers output.
Can load relative content with in the form of modules (views)
So I can manage better the different pages.
Bye!!

Related

Lithium PHP integration testing - routes.php not included?

I'm building a toy app in Lithium (PHP framework) based upon the Union of RAD's Framework project. It's all working great in the browser but when running integration tests, routes.php is not loaded, so the routing isn't working.
Here's the code I'm testing:
class StaffController extends \lithium\action\Controller {
public function add() {
$staff = Staff::create();
if (($this->request->data) && $staff->save($this->request->data)) {
return $this->redirect(array('Staff::view', 'args' => array($staff->id)));
}
return compact('staff');
}
My test:
public function testAdd() {
//Router::connect('/{:controller}/{:action}/{:args}');
$request = new Request();
$request->data = array('name' => 'Brand new user');
$controller = new StaffController(array('request' => $request));
/* #var $response \lithium\action\Response */
$response = $controller->add();
$this->assertEqual(302, $response->status['code']);
}
Notice the commented out line - Router::connect('/{:controller}/{:action}/{:args}'); - if I uncomment that, it's all good.
What I'm puzzled about is why, when running in unit tests, app/config/routes.php (where I define my routes) isn't loaded. From what I can determine, app/config/bootstrap/action.php adds a filter to the "run" method of the Dispatcher which loads routes.php.
Of course, it's possible that I am totally missing the point here! I'd appreciate any guidance you can give me!
Lithium has a lithium\action\Dispatcher used for http requests and a lithium\console\Dispatcher for console commands.
I'm assuming you are running tests from the command-line. I'm looking at the "framework" project's app/config/bootstrap/action.php file (here on github).
It is only including the routes.php file for the lithium\action\Dispatcher which is not loaded from the command-line. The app/config/bootstrap/console.php also doesn't include routes.php for the console.
My suggestion is to edit the console.php file and change the filter to look like this:
Dispatcher::applyFilter('run', function($self, $params, $chain) {
Environment::set($params['request']);
foreach (array_reverse(Libraries::get()) as $name => $config) {
if ($name === 'lithium') {
continue;
}
$file = "{$config['path']}/config/routes.php";
file_exists($file) ? call_user_func(function() use ($file) { include $file; }) : null;
}
return $chain->next($self, $params, $chain);
});

Phalcon backup view path

Is there any way to pass through a secondary path to the views dir in phalcon?
in zend framework I think the syntax is
$this->view->addScriptPath('/backup/path');
$this->view->addScriptPath('/preferred/path');
so if there is a file in the preferred path it will use it, if not it will fallback through the chain.
I use this, for example, for mobile versions when most of the pages are the same, but some have to be significantly different and I don't want to have to duplicate all the views just for 2 or 3 variants
In phalcon I have tried sending an array to the view, but that just results in neither working
$di->set('view', function() use ($config) {
$view = new \Phalcon\Mvc\View();
$view->setViewsDir( array('/preferred/path/', '/backup/path/') );
return $view;
});
I've got this working by extending the Phalcon\Mvc\View\Engine\Volt
In the render($template_path, $params, $must_clean = null) method I set the alternative path, check if file is available and if so I switch the $template_path given with the alternative path. Then it's just a case of calling:
return parent::render($template_path, $params, $must_clean);
where $template_path contains the new (alternative) path.
If your alternative path might change on a per project basis and you need to set it in bootstrap, then rather than doing it when getting a "view" from di you would do it when getting volt.
Just remember that all views are rendered with that method so you will have to account for layout and partial views as well - depending on your implementation.
Example: (this has not been tested, it's based on a similar set up I have in my own code)
<?php
class Volt extends Phalcon\Mvc\View\Engine\Volt
{
private $skin_path;
public function render($template_path, $params, $must_clean = null)
{
$skin_template = str_replace(
$this->di->getView()->getViewsDir(),
$this->getSkinPath(),
$template_path
);
if (is_readable($skin_template)) {
$template_path = $skin_template;
}
return parent::render($template_path, $params, $must_clean);
}
public function setSkinPath($data)
{
$this->skin_path = $data;
}
public function getSkinPath()
{
return $this->skin_path;
}
}
In your bootstrap:
$di->setShared('volt', function($view, $di) {
$volt = new Volt($view, $di);
$volt->setSkinPath('my/alternative/dir/');
return $volt;
});
Many thanks to nickolasgregory#github who pointed me in the right direction.
Method proposed by #strayobject helps me also, but I've found that using extend or other statements inside volt templates dosn't work.
Here's refined solution that works with extend and include:
use Phalcon\Mvc\View\Engine\Volt;
class VoltExtension extends Volt
{
// Override default Volt getCompiler method
public function getCompiler()
{
if (!$this->_compiler) {
$this->_compiler = new VoltCompilerExtension($this->getView());
$this->_compiler->setOptions($this->getOptions());
$this->_compiler->setDI($this->getDI());
}
return $this->_compiler;
}
}
And
use Phalcon\Mvc\View\Engine\Volt;
class VoltCompilerExtension extends Volt\Compiler
{
public function compileFile($path, $compiledPath, $extendsMode = null)
{
$skinPath = $this->getOption('skinPath');
if ($skinPath) {
$skinTemplate = str_replace(
$this->getDI()->getView()->getViewsDir(),
$skinPath,
$path
);
if (is_readable($skinTemplate)) {
$path = $skinTemplate;
}
}
return parent::compileFile($path, $compiledPath, $extendsMode);
}
}
Usage:
$volt = new VoltExtension($view, $di);
$volt->setOptions(
array(
'compiledPath' => $config->application->cacheDir,
'compiledSeparator' => '_',
'compileAlways' => false,
'skinPath' => $config->application->skinPath
)
);
Please take a look at this phalcon framework update. It provides support for multiple view packages per website (you can have multiple websites). Users of the magento framework will find it easy to use:
https://github.com/alanbarber111/cloud-phalcon-skeleton

How to extend anchor() function to anchor_admin() in CodeIgniter?

I would like to create my own function called anchor_admin() based on anchor() function in CodeIgniter.
I was thinking like:
I have defined admin path in config.php file e.g. like this:
$config['base_url'] = '';
$config['base_url_admin'] = 'my-custom-admin-folder';
and then
I need somehow create a new anchor_admin() function that extends anchor() function.
so instead of typing:
<?php echo anchor('my-custom-admin-folder/gallery', 'Gallery', 'class="admin-link"'); ?>
I would type only:
<?php echo anchor_admin('gallery', 'Gallery', 'class="admin-link"'); ?>
But the output wold be always:
Gallery
Basically I only need to ad the config variable $this->config->item('base_url_admin') at the end of the url generated by the core anchor() function.
How to do that?
Which files do I nned to create and where to put?
I guess creating a helper is not the way to go.
Should I create a library or could it be put as a function within my MY_Controller file in core folder of my application that I already have created and I am using it to load some stuff already?
In CodeIgniter you can 'extend' helpers ('extend' being a catch all term in this case as they're not actually classes). This allows you to add your own helper functions that will be loaded with the standard ones (in your case, the URL Helper).
It's explained in the CodeIgniter docs here - http://ellislab.com/codeigniter/user-guide/general/helpers.html
In your case you would want to do the following:
1- Create the file MY_url_helper.php in application/helpers/
2- Create your anchor_admin() function as below:
function anchor_admin($uri = '', $title = '', $attributes = '') {
// Get the admin folder from your config
$CI =& get_instance();
$admin_folder = $CI->config->item('base_url_admin');
$title = (string) $title;
if ( ! is_array($uri)) {
// Add the admin folder on to the start of the uri string
$site_url = site_url($admin_folder.'/'.$uri);
} else {
// Add the admin folder on to the start of the uri array
array_unshift($uri, $admin_folder);
$site_url = site_url($uri);
}
if ($title == '') {
$title = $site_url;
}
if ($attributes != '') {
$attributes = _parse_attributes($attributes);
}
return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>';
}
3- Use the helper and function how you normally would:
$this->load->helper('url');
echo anchor_admin('controller/method/param', 'This is an Admin link', array('id' => 'admin_link'));
Hope that helps!

Rendering a Static Page in Yii that resides in the Current Theme's Views

Ok I have a controller class in Yii that I want to use a different view folder aside from using its default view folder.
The natural behavior is when a $this->render("<view file>"); you would use the following to navigate your view file in the project...
"//" navigates project default view folder
"/" navigates current theme view folder
or do not use anything to select a view automatically in the
controller's default view folder
but my problem is i'm not rendering a view file but a STATIC PAGE that resides in /pages folder of a certain view folder. The static page I want to navigate is a static page the resides in my current theme folder views but the default is the controller navigates the static page inside the /protected/view folder
I tried also this override to modify the controller's view folder. I put this code in my controller that I want to render static pages in a theme folder
public function init(){
$this->layout = "//layouts/script";
$this->viewPath = "/js";
}
but the problem is the viewPath is readOnly variable.
Now my question is how I can render static pages that resides in my current theme's view folders?
NOTE: please if you don't understand my question, please don't down vote. I'm open to change and explain my problem for you as possible as I can
When you're overriding the actions method in your SiteController, somehow, you need to change the CViewAction's basePath property. It defaults to pages, as the documentation says.
Could you try something like this?
public function actions()
{
return array(
'page'=>array(
'class'=>'CViewAction',
'basePath'=>'path/to/your/theme/folder'
),
);
}
create a helper class for yourself and declare this method (change filepaths and other stuff):
public static function renderInternal($_viewFile_, $_data_ = null, $_return_ = false) {
// we use special variable names here to avoid conflict when extracting data
if (is_array($_data_)) {
extract($_data_, EXTR_PREFIX_SAME, 'data');
} else {
$data = $_data_;
}
$viewsDir = '/protected/views/internals/';
if ($_return_) {
ob_start();
ob_implicit_flush(false);
require(getcwd() . $viewsDir . $_viewFile_ . '.php');
return ob_get_clean();
} else {
require(getcwd() . $viewsDir . $_viewFile_ . '.php');
}
}
Use it/call it:
MyHelperClass::renderInternal( 'myviewfile', array( /* YOUR DATA */ ), /* RETURN CONTENTS OR NOT */ )
NOTE: Change $viewsDir to your desired directory.
try this in your any site controller or any controller..
public function actions()
{
return array(
'page'=>array(
'class'=>'CViewAction',
),
);
}
or refer this link...
http://www.yiiframework.com/wiki/22/how-to-display-static-pages-in-yii/

Zend - refactoring to include a form globally on site

I currently have a search form in the search controller, so the only way I can get to it is through /search/. I have to refactor my code so that this search form appears not only in the Search Controller but also globally throughout the site.
( The code isnt exact as I had to retype some of it )
My class that extends Zend_Form is located in application/forms/forms/SearchForm.php:
class Form_SearchForm extends Zend_Form {
public function init() {};
}
My search controller is something like..
class SearchController extends Zend_Controller_Action
{
public function search() {
$searchForm = new Form_SearchForm();
$this->view->form = $searchForm;
}
}
In my Bootstrap.php I have an autoloader for models:
protected function _initAutoload() {
$autoLoader = Zend_Loader_Autoloader::getInstance();
$resourceLoader = new Zend_Loader_Autoloader_Resource(
array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
'resourceTypes' => array(
'form' => array(
'path' => 'forms',
'namespace' => 'Form_',
),
'model' => array(
'path' => 'models/',
'namespace' => 'Model_',
),
),
)
);
return $autoLoader;
}
I'm wondering where I can store my code so that globally the search form is generated in the view.
My global layout file is located in application/layouts/scripts/layout.phtml and currently spits out a dynamic content area:
<div id="main">
<?php echo $this->layout()->content;?>
</div>
Should I just add the form to this layout.phtml or is there some generic controller I should use?
Edit: Sorry for not specifying this too, but what if for example I wanted to not include it for 1-2 special pages ( maybe an admin section ).. if I hardcoded it into layout.phtml it would still appear.. or should I serve a different layout file to say, an admin area?
Creating a searchAction() is not good for performance because it requires a brand new dispatch cycle. If, and only if, you have very complex logic that justifies a separate action, you could create a Controller Plugin and add searchAction() to the ActionStack. If you are only instantiating/assigning the form or if you don't need the search form for every request, it's not an optimal solution.
Another possibility would be to instantiate and assign the form in the bootstrap. This kind-of breaks separation of concerns, but provides better performance.
protected function _initSearchForm()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$searchForm = new Form_SearchForm();
$view->searchForm = $searchForm;
return $searchForm;
}
Finally, my preferred solution would be a custom view helper:
<?php
class My_View_Helper_SearchForm extends Zend_View_Helper_Abstract
{
public function searchForm()
{
$searchForm = new Form_SearchForm();
return $searchForm;
}
}
For either of these solutions, you'd ideally output the form in your layout file to minimise duplication.
layout.phtml:
<?php echo $this->searchForm() ?>
And create an alternate layout admin.phtml for admin area pages. This gives you the flexibility to change the admin pages significantly when new requirements pop up.
You can create your Form in a Controller Plugin and add it to view vars somehow (by Zend_Controller_Front?), which are accessible in layout, too. But it's too complicated in current ZF version (or I'm too dumb)
You can make Form_SearchForm a singleton
class Form_SearchForm ... {
static function getInstance() {
static $instance;
if (!$instance)
$instance = new Form_SearchForm();
return $instance;
}
}
Now instead of creating new Form_SearchForm() just get it as
$form = Form_SearchForm::getInstance();
You can put an instance of Form_SearchForm to the registry
I probably have missed a very cool a simple way :)
I would split it into a partial and a place holder.
in layout.phtml:
<?php if($searchForm = $this->placeHolder('searchForm'): ?>
<?php echo $searchForm; ?>
<?php endif; ?>
then in your views you can call:
<?php $this->placeHolder('searchForm')->set($this->partial('search-from.phtml', 'search')); ?>
IF you wanted you could even make a search view helper that basically does the place holder call.
The Controller plugin would be better if you have more pages that dont need it than d though. I would still probably use placeholder though to accomplish it. That way you can easily override or append to it later on a view-by-view basis without calling anything on the front controller.

Categories