define custom variables and direct call the variables in view part - php

What I want to do is creating a file like my_custom_settings.php in config directory and call the defined variable in view part.
let's say in my_custom_settings.php:
define('TEMPLATE_DIR', 'assets/front');
and in view part direct in HTML:
<link href="<?=TEMPLATE_DIR?>/stylesheet/style.css">
or any other alternative solution??
PS: Now I am using base_url() to access the path

personally i extend the /core/helpers/url_helper.php , defaults are site_url() , base_url(), current_url(); etc ... i just extended that for having base_static_url();
so put in core/helpers/url_helper.php:
if ( ! function_exists('base_static_url'))
{
function base_static_url()
{
$CI =& get_instance();
return $CI->config->slash_item('base_static_url');
}
}
then in config.php file you just add 1 more line:
$config['base_url'] = "http://mysite.com/";
$config['base_static_url'] = "http://mysite.com/static/"; //path to your static resources folder
then you can call static resources using :
<img src="<?php echo base_static_url();?>img/myimage.png"/>

ok this is might be more then what you are looking for,
but this is a way to put site wide configs in one file, and then easily have them available
in config folder you have file: my_custom_settings.php
in that file you want to set a config value like:
$config['TEMPLATE_DIR'] = 'assets/front' ;
$config['site_slogan'] = 'Laravel? Never heard of it' ;
create another file called: My_custom_settings.php
put that file in: application/library/My_custom_settings.php
that file will contain:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class My_custom_settings
{
function __construct($config = array() )
{
foreach ($config as $key => $value) {
$data[$key] = $value;
}
// makes it possible for CI to use the load method
$CI =& get_instance();
// load the config variables
$CI->load->vars($data);
}
} // end my custom settings
now in your controller constructor
public function __construct() {
parent::__construct();
// Load configs for controller and view
$this->load->library( 'my_custom_settings' );
$this->config->load( 'my_custom_settings' );
} // end construct
Now for the cool part -- anything you put in that config file, will be available for your controller and views. ( you can load config in a model constructor as well ).
in a controller or model you get the value with $this->config, like
$this->config->item( 'site_slogan' )
a little awkward, but for views, heres the reward, you only need the config name
echo $TEMPLATE_DIR . '/somefile' ;

Images, css, javascript, pdfs, xml... anything that is allowed to be accessed directly should not be living in your application directory. You can do it, but you really shouldn't. Create a new folder at the root of your directory for these files, they should not be mixed into your application, for example: in your views folder.
Chances are, you're using an .htaccess file, which is only allowing certain directories to be accessed via http. This is very good for security reasons, you want to stop any attempt to access your controllers and models directly. This is also why we check if BASEPATH is defined at the top of most files, and exit('No direct script access.') if not.
To get the correct path to these resources (js/css/images), you can't use relative paths, because we aren't using a normal directory structure. The url /users/login is not loading files from the directory /users/login, it probably doesn't even exist. These are just uri segments that the bootstrap uses to know which class, method, and params to use.
To get the correct path, either use a forward slash (assuming your app and assets are in the root directory, not a subdirectory) like this:
Or your best bet, use an absolute url:
// References your $config['base_url']
" />
Equivalent to:
http://mydomain.com/images/myimage.jpg
There are helpers built into CI that you can optionally use as well, but this is really all you need to know.

Related

Zend 2:: getting public folder path or basePath() easily in controller action

In my application, to move a file to a specific directory i need to know public folder path in controller action. I read different this type solution but not getting easy one. I know that in view we can get easily public folder path using $this->basePath(); view helper. I exactly want this in controller action. Anybody can guide me how can i achieve that. Thanks in advance.
index.php sets the current working dir to you application root (the folder containing composer.json, init_autoloader.php, etc.)
As long as you haven't called chdir elsewhere in your application you can call getcwd() and it'll always return the path to your app root.
Since the public folder is relative to that, you can get the path using ...
$publicDir = getcwd() . '/public';
In your public folder edit your file named index.php
add only two lines
define('BASE_PATH', realpath(dirname(__DIR__)));
define('PUBLIC_PATH', BASE_PATH.'/public');
you can use in your code like
print_r(BASE_PATH);
print_r(PUBLIC_PATH);
If you want to include a file from public folder (independence with location of index.php file):
include_one ("./public/your-file.php");
You should try this if you want the public folder:
$publicPath = $_SERVER['DOCUMENT_ROOT'];
Or try this if you want the basepath:
$basePath = dirname($_SERVER['DOCUMENT_ROOT']);
You could use view helpers from within a controller in ZF2 as it shown here and here. You may try this for your case :
$renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
$url = $renderer->basePath('the_ressource_you_want_to_get_from_public_folder');

CodeIgniter not working with multiple level subfolders for both controllers and views

I am working in Codeigniter with smarty templates.
Problem is that if i go about 2nd subfolder in view or controller, the Codeigniter stops working...
e-g here
application/controllers/main.php - works
application/controllers/admin/dashboard.php - works
application/controllers/admin/manageUsers/ListUsers.php - not working
I have searched the web, and they said that i can work with routes, which might do work with controller..
but it is views that i am concern of..
i mean admin views should go under admin folder, but i can not create subfolder in admin, if i put all views in admin folder, it will be a mess, nothing organized. i hope you are understanding what i am trying to say.
e-g
themes/default/views/home.tpl - works
themes/default/views/admin/dashboard.tpl works
themes/default/views/admin/site_settings/preferences.tpl not working
please can anyone guide me how to fix these issues.
Your problem is quite common. I've had it when I started working with CodeIgniter as well. What I found out to be the best way to overcome it, was to create a Custom_Router, which extends the CI_Router class. Doing that allows you to overwrite the controller class include/require logic and allow the usage of subdirs. This is a working example:
<?php
class Custom_Router extends CI_Router
{
public function __construct()
{
parent::__construct();
}
public function _validate_request($segments)
{
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
while(count($segments) > 0 && is_dir(APPPATH.'controllers/'.$this->directory.DIRECTORY_SEPARATOR.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->directory = $this->directory . $segments[0] .DIRECTORY_SEPARATOR;
$segments = array_slice($segments, 1);
}
if (count($segments) > 0)
{
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
show_404($segments[0]);
}
}
?>
The code above works fine with as many subdirs as you'd want, although I wouldn't advice using this approach. I usually specifically state the path to my controllers in the route.php file.
Regarding your second problem - the templates. I never liked messy code and even messier viewers which contain <?php echo $something; for(...){}; foreach(){}... ?> all over the place. For me, that makes the code really hard to read and specially harder to debug. That's why I've been using the Twig template engine. There are tutorials how to get it working in CodeIgniter (I've used this one). Once you're done with it, in your controller you would simply need to write:
class Login extends Custom_Controller
{
/**
* Index Page for this controller.
*/
public function index() {
$data = array();
$error_message = "Invalid user!";
if($this->session->getUserId() != null){
redirect('/welcome');
}
// other logic....
// depending on how you configure twig, this will search for "login.html.twig"
// in "application/views/". If your file is located somewhere in the subdirs,
// you just write the path:
// admin/login.html.twig => application/views/admin/login.html.twig
$this->twig->display('login.html.twig', $data);
}
}
If Twig is not an option for you, then you will need to create a new class which extends the CI_Loader class and overwrite the public function view(){} method.
By the way, if you're creating a web application with a backend, you might find it easier to manage and maintain your code if you separate your applications in different directories. If you choose to go this way, you will need to create application/public and application/admin folders preserving the directory structure of a CodeIgniter "application". Here are the steps:
Create separate applications
/applications
-- public (a standard application directory structure)
---- cache
---- config
---- controllers
---- models
---- views
---- ...
-- admin (a standard application directory structure)
---- cache
---- config
---- controllers
---- models
---- views
---- ...
Open /index.php and change $application_folder to point to applications/public
Create a copy of /index.php, name it backend.php (or whatever you want). Open the file and change $application_folder to point to the applications/admin folder.
Open .htaccess and add a rule to pass all URI starting with /admin to backend.php
# Route admin urls
RewriteCond %{REQUEST_URI} admin([/])?(.*)
RewriteRule .* backend.php?$1 [QSA,L]
Put THIS file into application/core/
Filename must be MY_Router.php

Mobile version of site using CodeIgniter

What I want to do is to create a mobile version of my web site in CodeIgniter.
I want to redirect my complete web site to m.example.com
There will be no change in controllers, neither in views and models. Both will be the same.
I don't want to change my .htaccess file. Any possible solutions for this?
The user agent class has a function;
$this->agent->is_mobile();
You could use this in the construct of your base controller(s) to test if mobile.
Instead of rewriting your code all over the place, you can just load a different view folder. In essence what will happen is you can just have CodeIgniter load a different view with the same name from another folder everytime you use $this->load->view("xxx"). First, create a new folder in your view folder called /mobile and just create views with the same exact naming conventions and it will load the the view accordingly by extending the Loader.php class.
Whether you are doing a responsive design or if you are going to create an iPhone app looking mobile version of your site, kind of like what facebook does, then you can just override the Loader class in the core folder. In your application/core folder create a MY_Loader.php and put it in that file.
Mine looks like the following
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Loader extends CI_Loader
{
//overides existing view function
function view($view, $vars = array(), $return = FALSE)
{
$CI =& get_instance();
$CI->load->library("user_agent");
if($CI->agent->is_mobile()){
$view = 'mobile/'.$view;
}
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
}
?>
Responsive web design is a mess in my opinion, but this still separates the code for you very nicely, while still being able to use your controllers and models in unison.
Hope this helps. This is the way I will be going about it :) !
Why a redirection? If everything is the same, why not look into Responsive webdesign?
24ways.org has some good articles for it:
http://24ways.org/2012/responsive-responsive-design/
http://24ways.org/2012/responsive-images-what-we-thought-we-needed/
Ok I found another solution. I used hooks pre controller and I redirect www subdomain to m subdomain.

CakePHP - How can i define route to a non-cakephp file that doesnt have any controllers associated with it?

Im working in CakePHP now. I'd like to know how i can define a route to a non-cakephp file that doesnt have any controllers associated with it?
I have placed this file(sitemap.php) in webroot folder, for my convenience. Now i need to route to it somehow!
It sounds like you want to be able to use functionality from sitemap.php in your cakephp application. The bet way to include this in cakephp is by setting it up as a vendor. Follow these steps:
1- Put the file in the app/vendor folder.
2- To use the file in a controller (or anywhere else), add:
App::import('Vendor','sitemap');
If it is just a file with a list of functions, you can now simply call the functions as you would in any other PHP file. So if you have a function called show_links() for example, in the controller where you have imported the vendor/sitemap, you simply put:
show_links();
If it is a class, then you will need to instantiate the class and use it like you would anywhere else:
App::import('Vendor','sitemap');
$sitemap = new Sitemap;
$sitemap->show_links();
So, now you are ready to set up the route to include the sitemap functionality in the config/routes.php file:
Router::connect('/sitemap.xml', array('controller' => 'YOUR_CONTROLLER', 'action' => 'YOUR_ACTION'));
This will process the sequence of code contained in the action that will then play off the sitemap.php file.
So in a nutshell, you would see something like this:
<?php
class SiteMapController extends AppController
{
var $name = 'Tests';
function show_map()
{
App::import('Vendor','sitemap');
$sitemap = new Sitemap;
$sitemap->show_links();
}
}
?>
And in the config/routes.php you would add:
Router::connect('/sitemap.xml', array('controller' => 'site_maps', 'action' => 'show_map'));
Then, when you visit the url:
http://mysite/sitemap.xml
It will route to:
http://mysite/site_maps/show_map
For more information on routing, you can visit: http://book.cakephp.org/view/542/Defining-Routes
Good luck and Happy Coding!
UPDATED!
I'd skip the whole CakePHP process if you're not actually using it. Unless your .htaccess is overly greedy (rewriting requests to file that * exist*), you should be able to access sitemap.php directly. If you can't, update the .htaccess file to not rewrite existing files.
Now, if external services need the file to be `sitemap.xml', don't try to do the rewriting in CakePHP, just rewrite with the .htaccess file (which by your comments, perhaps you're doing?).
The bottom line: Don't rewrite unless you have to, and don't rewrite with CakePHP if you're not even using it.

Zend Framework - shared view script path ( global partials )

How is it possible to set up a shared view script path for partials to create global partials within the Zend Framework?
We know that you can call partials between modules
e.g - echo $this->partial('partial_title','module_name');
but we need to set up a partial folder in the root ( i.e below modules) so that it can be accessble by all views.
It has been suggested to set up a shared view script path, how is this done?
Zend_View has a method called addScriptPath, so in a Zend_Controller_Action subclass you could do something like:
$this->view->addScriptPath("/path/to/your/view/scripts/");
Now when you call render or partial or partialLoop, that path will be included in the paths.
I have got a solution. We can do this by specifying the location of the view:
Calling partial as above form Module/Controller page
Method 1:
$this->view->addScriptPath("/ModuleConatinerDirectory/ModuleName/view/scripts/");
Then load using:
$message = $this->view->partial('templates/default.phtml','contact',array('var'=> 'var');
For the second option, please read the following:
http://framework.zend.com/issues/browse/ZF-6201
Now my doubt is, whether it is possible on setting it directly on Bootstrap file for all my Modules ? If so, how can I set this for two modules Module1 and Module2
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper( 'viewRenderer' );
$viewRenderer->setViewBasePathSpec( '/some/absolute/path/to/templates/:module/' );

Categories