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

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!

Related

How to check if the default configuration has been loaded in CI3?

I am working in a custom library for a project to be used in CI3.1 (CodeIgniter 3.1). This is a piece of code:
class NavigationMenu
{
protected $CI;
public function __construct($params = ['config' => 'navigation'])
{
$this->CI =& get_instance();
$this->CI->load->helper('url');
$this->CI->config->load($params['config'], true);
$this->CI->load->model('nav_model', 'nav');
}
....
}
The default config 'navigation.php` file have the following code:
$config['navigation_open'] = '<ul class="nav">';
$config['navigation_close'] = '</ul>';
$config['item_open'] = '<li>';
$config['item_open_active_class'] = 'active';
As you can see I am loading the url helper, the navigation config file and the nav_model model. Is there any way to check if them has been loaded previously? Could be the case when I want to save time and then setup the autoload.php as follow:
$autoload['helper'] = ['url'];
$autoload['config'] = ['navigation'];
$autoload['model'] = ['nav_model'];
If that's the case how do I check if has been loaded in order to not try to load once again?
I have look over the documentation for config class and couldn't find anything helpful
You can check is any function from url helper available at the moment, so You'll be able to understand was helper loaded or You should do it by Yourself:
if(!function_exists('site_url'))
$this->CI->load->helper('url');
It's an easy trick if You need to check is any helper was loaded, but it's not too clear how to check is config/model loaded, so if You really want to create Your own autoloader, You need to do similar checks with the core object ($this->CI):
if(!method_exists($this->CI,'nav'))
$this->CI->load->model('nav_model', 'nav');

call a function in themes in yii

I have a file in my yii first project. my project has a new theme with this path
first_proj\themes\project\views\layouts\main.php
and i want to call a function in it like below
<?php
if($is_project_manager){
?>
<div class="each-pop-el" style="cursor:pointer" ng-click="showAllMemberTask()">show tasks</div>
<?php } ?>
and have function in
first_proj\protected\controllers\project.php
this is
public function actionIsProjectmanager(){
$project_manager = false;
$crt = new CDbCriteria;
$crt->condition = 'user_id=:uid and role=1';
$crt->params = array('uid'=>Yii::app()->user->id);
$project_manager= projectMember::model()->findAll($crt);
// $model_result = MyModel::model()->test();
$this->render('the url to theme and main.php file', array('is_project_manager' => $project_manager));
}
how can i reach to that main.php file ? what i must write instead of
the url to theme and main.php file in my function ?
You set the controllers layout to the file. So it would look like this:
$this->layout = 'main';
Layouts must be rendered with a view file as well though.
$this->render('index', array('is_project_manager' => $project_manager));
Then place an index.php file in your views/project folder with the actions content.
This assumes you've setup your config to have the theme as project
First thing you need to know is: No need to pass layout file to the view. When you use render() function, yii automatically add layout to your view. Then, For specifying the layout, you need to use $this->layout = '//layouts/main in your action.
use this in your view
<?php
if($this->isProjectmanager){
?>
<div class="each-pop-el" style="cursor:pointer" ng-click="showAllMemberTask()">show tasks</div>
<?php } ?>
and create a helper function (not an action!) in your controller
public function IsProjectmanager(){
if ($someConditon) {
return true;
}
else {
return false;
}
}

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/

How to combine / integrate CodeIgniter and Wordpress blogs functionality?

My website having feature requirement of blogging. I have to make blog which would look same like my website appearance.
How to combine CodeIgniter and Wordpress blogging(only) functionality such that it should look like within same website?
I have seen this question: Wordpress template with codeigniter. But didn't got much clue.
Seems like a bit of overkill.
Why not use a Restful service like json_api to retrieve your posts, then copy over the css file(parts)?
You do this you will need to create 2 files and modify 2 existing functions. One function is in CodeIgniter and the other is in Wordpress.
Here are the steps.
1.) Open your configs/hooks.php file and create a pre_controller hook as follows:
$hook['pre_controller'] = array(
'class' => '',
'function' => 'wp_init',
'filename' => 'wordpress_helper.php',
'filepath' => 'helpers'
);
2.) Create a new file in your helpers directory called 'wordpress_helper.php', and add the following code to it:
/**
*
*/
function wp_init(){
$CI =& get_instance();
$do_blog = TRUE; // this can be a function call to determine whether to load CI or WP
/* here we check whether to do the blog and also we make sure this is a
front-end index call so it does not interfere with other CI modules.
*/
if($do_blog
&& ($CI->router->class == "index" && $CI->router->method == "index")
)
{
// these Wordpress variables need to be globalized because this is a function here eh!
global $post, $q_config, $wp;
global $wp_rewrite, $wp_query, $wp_the_query;
global $allowedentitynames;
global $qs_openssl_functions_used; // this one is needed for qtranslate
// this can be used to help run CI code within Wordpress.
define("CIWORDPRESSED", TRUE);
require_once './wp-load.php';
define('WP_USE_THEMES', true);
// Loads the WordPress Environment and Template
require('./wp-blog-header.php');
// were done. No need to load any more CI stuff.
die();
}
}
3.) Open wp-includes/link-template.php and made the following edit:
if ( ! function_exists('site_url'))
{
function site_url( $path = '', $scheme = null ) {
return get_site_url( null, $path, $scheme );
}
}
4.) Copy url_helper.php from the CodeIgniter helper folder to your APPPATH helper folder
and make the following edit:
if ( ! function_exists('site_url'))
{
function site_url($uri = '', $scheme = null)
{
// if we are in wordpress mode, do the wordpress thingy
if(defined('CIWORDPRESSED') && CIWORDPRESSED){
return get_site_url( null, $path, $scheme );
}else{
$CI =& get_instance();
return $CI->config->site_url($uri);
}
}
}
The steps above will allow you to dynamically load either your CI app or your WP site based on some simple filtering. It also gives you access to all CI functionality within WP of that is something you can use.

how to auto load mobile templates by agent in codeigniter?

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!!

Categories