In CodeIgniter I often have many scripts inherent to my project, for instance:
<?php
// Load many things
$this->load->model('news_model');
$this->load->helper('utility_helper');
$news = $this->news_model->get_basic_news();
// For moment no news
$view_datas['news']['check'] = false;
if ($news) {
$view_datas['news'] = array(
'check' => true,
'news' => _humanize_news($news)
);
}
?>
This script is used in different controllers, at the moment I create a scripts folder and I import it like that: include(APPPATH . 'scripts/last_news.php'); I'm quite sure it's not the best way to handle this problem. Any thoughts on that?
Update:
A solution given in the answers is to use a helper or a library.
Let's imagine a rewrite of my previous code:
class Scripts {
public function last_news() {
// Load many things to use
$CI =& get_instance();
$CI->load->model('news_model');
$CI->load->model('utility_helper');
$news = $CI->news_model->get_basic_news();
// Avoid the rest of code
}
}
Just create a new library and load that library whereever you require?
e.g.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Newclass {
public function get_news($limit)
{
//return news
}
}
/* End of file Newsclass.php */
In your controllers
$this->load->library('newsclass');
$this->newsclass->get_news($limit);
Or another idea is to create helper functions.
Related
I started working on a platform on CodeIgniter thanks to my work. The platform was started since before, so i just took the project. The thing is that i hadn't work with CI, so i just had a fast tutorial, and started developing based on how the platform was built. Now, to start, i decided to make a new page to to put a list of objects and understand a little how the PHP communicated with the HTML. The problem is that, when i go to the URL that i defined on routes.php, it gives an error "Requested resource does not exist", and i don't know what i'm doing wrong, while something similar works on other modules of the platform.
The files i'm using are:
list.php
// stuff
<?php if (has_access('agroindustrias')): ?>
<li class="<?php get_li_class('agroindustrias', $active); ?>" >
Agroindustrias
</li>
<?php endif ?>
// stuff
agroindustria.php
<?php
if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
class Agroindustria extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('agroindustria_model', 'agroindustria');
}
public function index($offset = 0)
{
$data['links'] = $this->paginate($this->agroindustria, 'agroindustrias', $offset);
$data['permisos'] = $this->getPermissions('usuario');
$data['active'] = 'usuarios';
$data['agroindustrias'] = $this->agroindustria->limit($this->limit, $offset)->get_all();
$data['submenu'] = $this->load->view('administracion/menu', $data, true);
$this->template->write_view('content', 'administracion/agroindustrias/list', $data);
$this->template->render();
}
}
routes.php(Updated with all the file, only the one before "reportes" doesn't work)
$route['administracion/agroindustria'] = 'agroindustria/index';
My URL is: http://localhost/work/administracion/agroindustria
The other controllers works with something similar, reason that i don't know what i'm doing wrong, if i still need to add something to another file, or if something that i wrote is wrong. Thanks in advance.
After the things that #Antony told me to check, i was able to find the error, it wasn't actually an error, just that the people before worked very much in the platform, that i did not undertand the mothodology to add new modules to the platform. All that i needed to do was register the new module, and the platform added the new URL as i wanted. Thanks Antony for your help!
1st of all rename agroindustria.php to Agroindustria.php if 1st letter not in upper case
if you are using method like this
public function index($offset = 0){
....
....
....
}
then you need to change routes like
$route['administracion/agroindustria/(:num)'] = 'agroindustria/index/$1';
and url
http://localhost/work/administracion/agroindustria/0
The best solution is change in your controller
//if offset not change
public function index(){
$offset = 0;
....
....
....
}
//if your offset depend upon 3rd segments of URL then
public function index(){
$offset = if($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
....
....
....
}
I recently implemented the following MVC code using this tiny mvc boilerplate.
I did not want to use Zend or Symfony as I only require a small structure but i really need to expend this one slightly.
I am new to PHP so wondered if anyone has used this or knows how i go about adding another View. I have got the link version working which i use to load my layout but would like to add a Content section within this layout which is able to call other pages.
Any help with this would be great!
Gods below .. that video is horrible.
In that existing example, if you want to add another "view" (which is no really what view is), you will need another method in the controller:
class Controller
{
// -- snip --
// you need to change the constructor too
public function __construct()
{
$this->load = new Load;
$this->model = new Model;
}
// -- snip --
public function gallery()
{
$list = $this->model->get_urls();
if ( count($list) > 0 )
{
$this->load->view('gallery.php' , $list);
}
else
{
$this->load->view('error.php', array(
'source' => 'gallery',
'reason' => 'empty'
));
}
}
// -- snip --
}
And you also would need to change the tinyMvc.php file:
$c = new Controller;
$action = 'home';
if ( isset( $_GET['page']))
{
$action = $_GET['page'];
}
if ( method_exists( $c, $action) )
{
$c->{$action}();
}
else
{
echo 'no such action !';
}
Anyway. Whole that "tutorial" uses the terms of MVC, that isn't really whats made there. His "view" is actually just a simple template. Which is not completely a thing to learn how to do for a beginner, but his implementation sucked too .. If you want to learn how to make simple native php templates, you might find this article quite useful.
NOTE: UPDATED MY QUESTION
I am using zend.I have the file "stylesettings.php" under css folder. Having the following line to convert php file to css.
header("Content-type: text/css");
stylesetting.php is under application/css/stylesettings.php
Now i want to get the color code from my DB in stylesettings.php.Here i can write basic DB connection code to get values from DB. I guess there might be another way to get all DB values by using zend. How can we connect DB like "Zend_Db_Table_Abstract" in stylesettings file ?
Is it possible to use zend component in that file ? Kindly advice on this.
I hope you understand.
You are breaking the basic separated model assumed in a MVC framework. For such color code, if it's only used in one place, I would suggest that you output the color in the "style="color: <color>"" in-line style in order to keep the dynamic part in HTML and your CSS file static.
If you really want to do this, then you should consider output your dynamic stylesheet in a URL path other than css, and use the controller/views etc to generate the stylesheet.
i am using the following way to apply color settings in layout.phtml
Use below code in bootstrap file
<?php
require_once 'plugins/StyleController.php';
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initRouter() {
$front = Zend_Controller_Front::getInstance ();
$front->setControllerDirectory ( dirname ( __FILE__ ) . '/controllers' );
$router = $front->getRouter ();
$front->registerPlugin ( new StyleController ( $router ) );
}
}
Created folder plugins under application and create a new file called stylecontroller.php
<?php
class StyleController extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
/* code for getting color settings */
$this->settings = new Admin_Model_DbTable_Settings();
$view->colorsettings = $this->settings->getStyleSettings();
//print_obj($view->colorsettings);
}
}
?>
Also to get color code,
<?php
class Admin_Model_DbTable_Settings extends Zend_Db_Table_Abstract
{
public function getStyleSettings()
{
$select = $this->_db->select()
->from('style_settings');
$result = $this->getAdapter()->fetchAll($select);
return $result['0'];
}
}
?>
By using above code i can able to use $this->colorsettings in layout page.
This one fix my dynamic color in layout but not in other template files.
How do people construct websites with cake/CI ect... for easy maintenance on the html?
I can put each of the sections in its own view file and make the website that way:
<div id="header"></div> <!-- header_view.php -->
<div id="content"> <!-- header_view.php -->
<div id="left_column"></div> <!-- page_x_view.php -->
<div id="center_column"></div> <!-- page_x_view.php -->
</div>
<div id="footer"></div> <!-- footer_view.php -->
But each page_x_view.php file would contain
<div id="left_column"><!-- Content --></div>
<div id="center_column"><!-- Content --></div>
And I'm duplicating these items through each of the files, so if I need to change the column structure then it is not easy.
Hopefully I am clear.
I have a controller caled MY_Controller which has a method that renders the complete page. I extend all my controllers from this main controller. HOw this helps? My main controllers takes a view and embedds it in the main content area of page and assembles a complete page. This controller takes header, footer, sidebar views and does all the mambo jumbo. Its very easy to develop such a system in CI. Some this call two step or multiple views. So if some random day I have to change layout of my page I just need to look at MY_Controller.
Cake on the other side uses layouts. I have done just one project in CakePHP so am not that expert but you can achieve the same effect in any framework. Here is how I do it in CI
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
log_message('debug', 'Controller Library '.__CLASS__ . ' ('. __FILE__ .') loaded.');
$this->properties['viewPath'] = $this->config->item('viewPath');
$this->setPageMetaData();
$this->setFavIcon();
}
public function render($viewData = null, $data=null)
{
$data = array(
'headerLayout' => $this->printHeaderLayout(array_merge($this->properties, (isset($data['headerLayout'])?$data['headerLayout']:array()))),
'leftLayout' => $this->printLeftLayout(array_merge($this->properties, (isset($data['leftLayout'])?$data['leftLayout']:array()))),
'rightLayout' => $this->printRightLayout(array_merge($this->properties, (isset($data['rightLayout'])?$data['rightLayout']:array()))),
'footerLayout' => $this->printFooterLayout(array_merge($this->properties, (isset($data['footerLayout'])?$data['footerLayout']:array()))),
'containerLayout' => $viewData,
);
this->load->view($this->properties['viewPath'].'layout/layout.php', $data);
}
public function setPageMetaData($pageMetaData=null)
{
$this->properties['pageTitle'] = isset($pageMetaData['pageTitle'])? $pageMetaData['pageTitle'] : $this->config->item('pageTitle');
$this->properties['pageKeywords'] = isset($pageMetaData['pageKeywords'])? $pageMetaData['pageKeywords'] : $this->config->item('pageKeywords');
$this->properties['pageDescription'] = isset($pageMetaData['pageDescription'])? $pageMetaData['pageDescription'] : $this->config->item('pageDescription');
}
public function setFavIcon($favIcon=null)
{
$this->properties['favIcon'] = (null !== $favIcon) ? $favIcon : $this->config->item('favIcon');
}
public function printHeaderLayout($data=null)
{
return ($this->load->view($this->properties['viewPath'].'layout/header', $data, true));
}
public function printFooterLayout($data=null)
{
return( $this->load->view($this->properties['viewPath'].'layout/footer', $data, true));
}
public function printLeftLayout($data=null)
{
return($this->load->view($this->properties['viewPath'].'layout/left', $data, true));
}
public function printRightLayout($data=null)
{
return($this->load->view($this->properties['viewPath'].'layout/right', $data, true));
}
}
Do note that this is not the exact code. I had to modify it for you, so do not blindly user it. If you know CI you will understand that I have setup paths to view in a config file. This helps me in setting up two totally different themes and use same controller. I can also add authentication layer which will based on user authentication/cookies can show a login or logout link in header. This is a template which I keep change and I extend all my controllers from MY_Controller and use in my controllers I simply do
$viewDataForForm = $this->load->view($this->properties['viewPath'].'homepage/some-form', array(), true);
$viewDataForContent = $this->load->view($this->properties['viewPath'].'homepage/some-content', array(), true);
$this->render($viewDataForForm.$viewDataForContent);
HTH!
Codeigniter and CakePHP take advantage of the Model View Controller configuration. They separate the database queries and data processing from the views. This provides an easy to use and easy to maintain way of coding. Multiply controllers can use the same view which helps cut down on the amount of code written and the complexity. Methods in the models can be reused which reduces bugs and amount of code written. And controllers provide and easy to follow way of reading and writing code. I am not sure if I answered your question but comment on my answer if you need and more explanation.
I am trying to implement CAS authentication in a CodeIgniter application though I cannot find if there are any libraries currently set up for it. I am managing by just including the class and adding in a few dirty fixes though if anyone knows of a proper library I think it would be a cleaner solution.
I have been looking through a range of posts on here as well as all over Google but seem to be coming up short on what I need. The only place of any relevance is a post on VCU Libraries but that did not include the library download link.
Thanks everyone!
UPDATE: You can find the latest version of the library at Github: https://github.com/eliasdorneles/code-igniter-cas-library
You can also install via sparks: http://getsparks.org/packages/cas-auth-library/versions/HEAD/show
I've started a CAS library to simplify setting up CAS authentication for CodeIgniter, that relies on the existing phpCAS.
To start using it, you just have installation phpCAS in some accessible directory, put the library file in application/libraries/Cas.php and create a config file config/cas.php like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['cas_server_url'] = 'https://yourserver.com/cas';
$config['phpcas_path'] = '/path/to/phpCAS-1.3.1';
$config['cas_disable_server_validation'] = TRUE;
// $config['cas_debug'] = TRUE; // <-- use this to enable phpCAS debug mode
Then, in your controllers you would be able to do this:
function index() {
$this->load->library('cas');
$this->cas->force_auth();
$user = $this->cas->user();
echo "Hello, $user->userlogin!";
}
Here is the library file (has to be named Cas.php):
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function cas_show_config_error(){
show_error("CAS authentication is not properly configured.<br /><br />
Please, check your configuration for the following file:
<code>config/cas.php</code>
The minimum configuration requires:
<ul>
<li><em>cas_server_url</em>: the <strong>URL</strong> of your CAS server</li>
<li><em>phpcas_path</em>: path to a installation of
phpCAS library</li>
<li>and one of <em>cas_disable_server_validation</em> and <em>cas_ca_cert_file</em>.</li>
</ul>
");
}
class Cas {
public function __construct(){
if (!function_exists('curl_init')){
show_error('<strong>ERROR:</strong> You need to install the PHP module <strong>curl</strong>
to be able to use CAS authentication.');
}
$CI =& get_instance();
$this->CI = $CI;
$CI->config->load('cas');
$this->phpcas_path = $CI->config->item('phpcas_path');
$this->cas_server_url = $CI->config->item('cas_server_url');
if (empty($this->phpcas_path)
or filter_var($this->cas_server_url, FILTER_VALIDATE_URL) === FALSE) {
cas_show_config_error();
}
$cas_lib_file = $this->phpcas_path . '/CAS.php';
if (!file_exists($cas_lib_file)){
show_error("Could not find file: <code>" . $cas_lib_file. "</code>");
}
require_once $cas_lib_file;
if ($CI->config->item('cas_debug')) {
phpCAS::setDebug();
}
// init CAS client
$defaults = array('path' => '', 'port' => 443);
$cas_url = array_merge($defaults, parse_url($this->cas_server_url));
phpCAS::client(CAS_VERSION_2_0, $cas_url['host'],
$cas_url['port'], $cas_url['path']);
// configures SSL behavior
if ($CI->config->item('cas_disable_server_validation')){
phpCAS::setNoCasServerValidation();
} else {
$ca_cert_file = $CI->config->item('cas_server_ca_cert');
if (empty($ca_cert_file)) {
cas_show_config_error();
}
phpCAS::setCasServerCACert($ca_cert_file);
}
}
/**
* Trigger CAS authentication if user is not yet authenticated.
*/
public function force_auth()
{
phpCAS::forceAuthentication();
}
/**
* Return an object with userlogin and attributes.
* Shows aerror if called before authentication.
*/
public function user()
{
if (phpCAS::isAuthenticated()) {
$userlogin = phpCAS::getUser();
$attributes = phpCAS::getAttributes();
echo "has attributes? ";
var_dump(phpCAS::hasAttributes());
return (object) array('userlogin' => $userlogin,
'attributes' => $attributes);
} else {
show_error("User was not authenticated yet.");
}
}
/**
* Logout and redirect to the main site URL,
* or to the URL passed as argument
*/
public function logout($url = '')
{
if (empty($url)) {
$this->CI->load->helper('url');
$url = base_url();
}
phpCAS::logoutWithRedirectService($url);
}
}
I recommend using Ion Auth Library, it's built upon Redux Auth, which became outdated. Ion Auth is light weight, easy to customize, and does the things you need. Ion Auth is one of the best authentication libraries for CodeIgniter.
What exactly is not working with the VCU library?
Anything you can do in PHP, you can do in CodeIgniter.
So you can just use the PHP CAS client:
http://www.jasig.org/phpcas-121-final-release
And here is a example of how to authenticate.
https://source.jasig.org/cas-clients/phpcas/trunk/docs/examples/example_simple.php