I'm having a problem loading modules inside my template library in CodeIgniter HMVC. The reason I want to load a module in the template library is that I wish to use modules for sideboxes and other content boxes in my template.
PS: I am also using the Smarty template parsing system for CodeIgniter, but I doubt it has anything to do with the errors, but if you have reasons to believe otherwise, please, let me know.
What I tried to do
I tried to load the module in two different ways, and both presented with the same errors.
The errors
A PHP Error was encountered
Severity: Notice
Message: Undefined Property CI::$template
File: MX/Loader.php
Line Number: 141
-
A PHP Error was encountered
Severity: Notice
Message: Undefined Property CI::$template
Filename: MX/Controller.php
Line number: 57
-
Fatal error: Call to a member function load_content() on a non-object in E:\Xampp\htdocs\firecms\application\modules\sidebar_login_box\controllers\sidebar_login_box.php on line 7
The undefined "load_content()" function will be explained further down (in Sidebar Controller).
The Error lines
MX/Loader
/*Line 140*/if (isset($this->_ci_classes[$class]) AND $_alias = $this->_ci_classes[$class])
/*Line 141*/ return CI::$APP->$_alias;
MX/Controller
/*Line 56*/public function __get($class) {
/*Line 57*/ return CI::$APP->$class;
How I tried to load the modules
This was my first attempt (loading the file and instancing its class):
class Template {
//[...]
public function load_sidebars()
{
$sidebars = $this->CI->cms_model->get_sidebars();
foreach ($sidebars as $sidebar)
{
if (trim($sidebar["content"]) == "")
{
//An example of sidebar module name is "sidebar:login_box"
//The function below changes the name to "sidebar_login_box" (the
//module's folder and controller name.
$module = str_replace(':', '_', $sidebar["module"]);
$file_path = APPPATH.'modules/'.$module.'/controllers/'.$module.'.php';
require_once $file_path;
$class = ucfirst($module);
$object = new $class();
$module_data = $object->index();
$this->_section_data["sidebars"][]["content"] = $module_data;
}
else
{
$this->_section_data["sidebars"][]["content"] = $sidebar["content"];
}
}
}
//[...]
}
And this was my second attempt (using the loader function):
public function load_sidebars()
{
$sidebars = $this->CI->cms_model->get_sidebars();
foreach ($sidebars as $sidebar)
{
if (trim($sidebar["content"]) == "")
{
$module = str_replace(':', '_', $sidebar["module"]);
$this->CI->load->module($module);
$module_data = $this->CI->$module->index();
$this->_section_data["sidebars"][]["content"] = $module_data;
}
else
{
$this->_section_data["sidebars"][]["content"] = $sidebar["content"];
}
}
}
The sidebar controller
This is how the sidebar controller looks like:
class Sidebar_login_box extends Fire_Controller {
public function index()
{
$view_data = array();
//The load_content function in the template library is used to parse template files
//and return them as a string.
return $this->template->load_content("login_box", $view_data);
}
}
The Fire Controller
The Fire_Controller is my core controller. My core classes' prefix is Fire_ instead of MY_.
This is how the fire controller looks like:
class Fire_Controller extends MX_Controller {
public function __construct()
{
parent::__construct();
//Load configurations from the database.
$this->config->load_db_configs();
//Set the timezone.
date_default_timezone_set(config_item("timezone"));
//Loads the form validation library.
$this->load->library("form_validation");
//Reset the Form Validation CI Object (to fix problems with HMVC CI).
$this->form_validation->CI =& $this;
//To reduce load time, the template library will not be loaded in ajax
//requests.
if ( ! $this->input->is_ajax_request())
{
$this->load->library("template");
}
//Force access via SSL connection (HTTPS) if necessary.
if ((int)config_item('force_https') === 1)
{
force_https();
}
}
Note: This is a very recent project of mine, which means that the framework and all third party extensions are in the most recent stable version as of January 06, 2015.
Thank you for your time,
Best regards.
Fixed.
The sidebars were loaded from the set_defaults() method, which was called by the constructor method in my template library. And since it wasn't fully loaded, the template object was not saved in CI's super object, thus being inaccessible and throwing the errors in the sidebar module.
I have moved the set_defaults() call to the render_page() function of my template library (which are called by the modules' controllers), and now it's working perfectly.
Too bad I added bounty a few hours before finding the solution, hehe.
You need to load the library before you can use it in the sidebar controller. It isn't being passed from the parent. Try this:
class Sidebar_login_box extends Fire_Controller {
public function index()
{
$view_data = array();
$this->load->library('template');
//The load_content function in the template library is used to parse template files
//and return them as a string.
return $this->template->load_content("login_box", $view_data);
}
}
Cheers!
Related
The name is quite bad, but I really don't know what else to call it.
I'm trying to make a extendable and modular plugin system for my website. I need to be able to access plugin php files that exist in a plugin directory and get access to their classes to call functions such as getting the html content that the plugin should show and more.
Below is a semi-pseudo code example of what I am trying to achieve, but how to actually arbitrarily load the plugins is where I am stuck (PluginLoader.php).
-Max
//BasePlugin.php
abstract class BasePlugin
{
public function displayContent()
{
print "<p>Base Plugin</p>";
}
};
//ExamplePlugin.php -> In specific plugin directory.
require('../BasePlugin.php');
class ExamplePlugin extends BasePlugin
{
public static function Instance()
{
static $inst = null;
if ($inst === null) {
$inst = new ExamplePlugin();
}
return $inst;
}
public function displayContent()
{
print "<p>Example Plugin</p>";
}
}
//PluginLoader.php
foreach($pluginFile : PluginFilesInDirectory) { // Iterate over plugin php files in plugin directory
$plugin = GetPlugin($pluginFile); // Somehow get instance of plugin.
echo plugin->displayContent();
}
I'm guessing here, but it seems to me that you need to:
get a list of the plugins in the desired directory.
include or require the plugin's class file.
create an instance of the class.
call the plugin's displayContent() method.
So, you probably want to do something like
$pluginDir = 'your/plugin/directory/' ;
$plugins = glob($pluginDir . '*.php') ;
foreach($plugins as $plugin) {
// include the plugin file
include_once($plugin) ;
// grab the class name from the plugin's file name
// this finds the last occurrence of a '/' and gets the file name without the .php
$className = substr($plugin,strrpos($plugin,'/') + 1, -4) ;
// create the instance and display your test
$aPlugin = $className::Instance() ;
$aPlugin->displayContent() ;
}
There's probably a cleaner way to do it, but that will ready your directory, get the plugins' code, and instantiate each one. How you manage/reference them afterwards depends on how your plugins register with your application.
I have an old project I'm working on using Slim version 2. I can not upgrade to 3.
I'm trying to integrate twig into slim 2 while also keeping the old default slim2 renderer.
Currently I have this.
class TwigView extends \Slim\View
{
public function rendertwig($template,$data = array()){
global $twig;
$twigResults = $twig->render($template,array('test' => '1'));
$data = array_merge($this->data->all(), $data);
return $this->render($twigResults, $data);
}
}
$view = new TwigView();
$config['view'] = $view; //#JA - This command overides the default render method.
//#JA - Intialize Slim
$app = new \Slim\Slim($config);
The idea is that I would call this saying $app->view->rendertwig('file.twig') when I need to render the twig templates and use $app->render('template.php') for all the other templates that use the default slim2 method of templating.
However, I get an error because in my rendertwig function $this->render() function requires a template name for the first parameter. Is there a way I can render directly the results from twig into the slim engine without needing a template file?
I'm aware this is bad form to have two templating engines but eventually I will switch everything to Twig but I need this as a temporary solution till I can patch everything over.
When I inspected slim's view object it has this defined as its render method which will explain the issue.
protected function render($template, $data = null)
{
$templatePathname = $this->getTemplatePathname($template);
if (!is_file($templatePathname)) {
throw new \RuntimeException("View cannot render `$template` because the template does not exist");
}
$data = array_merge($this->data->all(), (array) $data);
extract($data);
ob_start();
require $templatePathname;
return ob_get_clean();
}
I don't know if this is bad form but I did this as a temporary solution.
class TwigView extends \Slim\View
{
public function rendertwig($template,$data = array()){
global $twig;
$twigResults = $twig->render($template,array('test' => '1'));
echo $twigResults;
}
}
I saw that all the render method did was just require the template so I figured its safe to just echo the results from the twig templating engine? This seemed to work from my test.
I have a custom content type called "program" that I am trying to load via a drupal module.
The .module file includes a class called Program that has a method called
getAllPrograms() using include_once(drupal_get_path('module', 'progs') . '/progs.php');
When i try and load nodes using either node_load() or node_load_multiple() i get one of two different errors randomly.
either:
Fatal error: Fatal error: Call to undefined function user_access() in /mypath/modules/filter/filter.module on line 1035
or
Error: Call to undefined function token_get_entity_mapping() in /mypath//sites/all/modules/contrib/token/token.tokens.inc, line 767
Note: 99% of times it is the first error, and occasionally i would recieve the token_get_entity error.
The strange thing is, while i have been trying different things to resolve the error I have been able to get both of these functions to work for a period but as soon as i clear the Drupal Cache i get the error again.
What I have tried
Disabling and enabling the user module via the database.
Checking the paths and status are correct for the main modules (system, user, block etc)
using db_select to get a list of node ids and then use node_load() (with a loop) and node_load_multiple() to load the nodes. This is one of the things that started working for a short time until i cleared the cache.
Tested to see if i can call user_access() from my .module file. This does not work and returns the same call to undefined function error.
Here is the code that I have (not progs an anonymized name)
progs.module
include_once(drupal_get_path('module', 'progs') . '/progs.php');
progs.php
if( !class_exists('progs') ):
class progs
{
//a bunch of properties
function __construct()
{
// load partial includes and objects
$this->load_partial_inclues();
//retrieve all programs that are open
$this->open_programs = Program::getAllOpenPrograms();
}
function load_partial_inclues()
{
//includes
include_once(drupal_get_path('module', 'progs') . '/core/objects/program.php');
}
}
function progs()
{
global $progs;
if( !isset($progs) )
{
$progs = new progs();
}
return $progs;
}
// initialize
progs();
endif;
Note: I load the $progs into the global space so i can call it elsewhere in my module.
program.php
if( !class_exists('Program') ):
class Program
{
//a bunch of properties
public static function getAllOpenPrograms()
{
// This is the line that causes all of the issues.
$result = node_load_multiple('',array('type' => 'program'));
dpm($result);
}
Thanks in advance!
Like Mike Vranckx mentioned, if you call progs() directly when you include it in progs.module, Drupal basically hasn't bootstrapped, i.e. hasn't started running fully yet. Suggest you put your progs() in progs_init() or similar so that Drupal will invoke it at the right time.
Here's a proposed way that follows your initial structure quite closely, and below you will see an alternative that better follows Drupal's conventions.
New progs.module
/**
* Implements hook_init().
*/
function progs_init(){
progs();
}
And modify your progs.php
// Why are you doing this check? Are you defining this class elsewhere in your project? If not you can safely ignore this
//if( !class_exists('progs') ):
// Convention is to name classes with Pascal case btw.
class progs
{
//a bunch of properties
function __construct()
{
// load partial includes and objects
$this->load_partial_inclues();
//retrieve all programs that are open
$this->open_programs = Program::getAllOpenPrograms();
}
function load_partial_inclues()
{
//includes
include_once(drupal_get_path('module', 'progs') . '/core/objects/program.php');
}
}
function progs()
{
global $progs;
if( !isset($progs) )
{
$progs = new progs();
}
return $progs;
}
A more Drupal way:
progs.module
/**
* Implements hook_init().
*/
function progs_init(){
global $progs;
// Consider using drupal_static to cache this
if( !isset($progs) )
{
module_load_include('inc', 'progs', 'progs');
$progs = new Progs();
}
}
progs.inc (convention is to use .inc)
class Progs
{
//a bunch of properties
function __construct()
{
// load partial includes and objects
$this->load_partial_inclues();
//retrieve all programs that are open
$this->open_programs = Program::getAllOpenPrograms();
}
function load_partial_inclues()
{
//includes
module_load_include('php', 'progs', 'core/objects/program');
}
}
I'm trying to integrate Fotolia Api with Prestashop 1.6.0.9.
I already make module with custom tab, but I have no idea how set view from module folder for this tab. Sorry to say, but "documentation for developers" SUCKS.
I can't find any working solution.
public function install() {
if (!parent::install()
|| !$this->registerHook('backOfficeHeader')
|| !$this->registerHook('header')
) return false;
$tab = new Tab();
$tab->class_name = 'AdminFotoliaSelector';
$tab->id_parent = 0;
$tab->module = $this->name;
$tab->name[(int)(Configuration::get('PS_LANG_DEFAULT'))] = 'Fotolia Selector';
$tab->add();
return true;
}
I had big problem with make proper controller, and now I just can't load anything/ I have no idea how do this.
<?php
if (!defined('_PS_VERSION_'))
exit;
class AdminFotoliaSelectorController extends ModuleAdminController {
public $name;
public function __construct() {
$this->lang = (!isset($this->context->cookie) || !is_object($this->context->cookie)) ? intval(Configuration::get('PS_LANG_DEFAULT')) : intval($this->context->cookie->id_lang);
parent::__construct();
}
public function initContent() {
parent::initContent();
$this->renderForm();
}
public function renderForm() {
$path = _MODULE_DIR_."fotoliaselector";
$more = $this->module->display($path, 'views/templates/admin/fotoliaselector.tpl');
return $more.parent::renderForm();
}
When I try die($more) it gives me content of .tpl, anyway when I click tab in back office it's still empty.
I have debug options on, compiling on, cache off.
So just enlight me please, how am I supose to show ANYTHING there?
I think the problem is that you don't display tab's content at all.
I don't know what module->display method does, but I think you should change in initContent() method line:
$this->renderForm();
into
echo $this->renderForm();
If it won't help you should look at this documentation and try to do it without external classes - only try to use Smarty to display simple content without using Tab class or AdminFotoliaSelector
Well i know it will sounds weird but you need to take some similar modules, and read his code and will see some methods names are the same in each module.
Then copy that, install and play with some changes etc.
Imho you miss standard method getContent() form where you need to pass some data for smarty:
public function getContent()
{
global $smarty, $cookie;
......
//some code
......
$this->_html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>';
$this->_html .= '<h1>My module title or stuff</h1>';
$this->_html .= $this->getMyCoolFormOrConfig();
$smarty->assign('errors', $this->errors);
$smarty->assign('message', $this->message);
$this->_html .= $this->display(__FILE__, 'name_of_tpl_file.tpl');
return $this->_html;
}
to simple add tab in BackOffice code like this:
$id_tab=Tab::getIdFromClassName('AdminPayment');
$newtab=new Tab();
$newtab->id_parent=$id_tab;
$newtab->module=$this->name;
$newtab->class_name='MyClassName'; //will be same like MyClassName.php in folder of you module where you need to create you class and extend the AdminTab and from there with function you need to echo you name module
$newtab->position=Tab::getNbTabs($id_tab)+1;
$newtab->name[$cookie->id_lang]=$this->l("Name of you stuff");
$newtab->name[Configuration::get('PS_LANG_DEFAULT')]=$this->l("Name of you stuff");
$newtab->add();
Study this file there /controllers/admin/AdminModulesController.php
and you see what methods are using in each module
Take a look greater feature to generate you module structure (register requeired) https://validator.prestashop.com/generator
I hope someone can help me with this one before I jump off the window. I spent few hours on this one and don't know what am I doing wrong.
Basically, I've installed HMVC in CodeIgniter 2.1.2 and everything works fine, BUT for some reason I can't load models the same way I'm doing it in standard controllers. In the old codeigniter 1.7.1 I could use it simply by invoking $this->load->model('my_model') but now I can't?!
Every single time I'm trying to load model I get this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Special_cart::$db
Filename: core/Model.php
Line Number: 51
I have had installed it step-by-step according to the instructions. I got third_party next to modules folder. In modules I have few modules stored like this:
modules
--boxes
----controller
----models
----views
I invoke module in my code like this:
<?=modules::run('boxes/special_cart/index');?>
My module controller code looks like this:
class Special_cart extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
if ($this->session->userdata('cart'))
{
# get product id's and each quantity
$cart_product_list = array_count_values($this->session->userdata('cart'));
# get list of product_id
$product_list = array_keys($cart_product_list);
# get product details
$this->load->model('productmodel');
$this->load->model('stockmodel');
$cart_products = $this->productmodel->cart_get_products_details($product_list);
$final_cart_array = array();
foreach($cart_products as $cart_product){
$product_stock = $this->stockmodel->view_product_stock($cart_product["id"]);
if(empty($product_stock) || $product_stock["UNITS"]<=0)
$cart_product["UNITS"] = 0;
else{
if($cart_product_list[$cart_product["id_web"]]>$product_stock["UNITS"])
$cart_product["UNITS"] = $product_stock["UNITS"];
else{
$cart_product["UNITS"] = $cart_product_list[$cart_product["id_web"]];
}
}
$final_cart_array[] = $cart_product;
}
$refresh_cart_array = array();
foreach($final_cart_array as $cart_product){
for($i=1;$i<=$cart_product["UNITS"];$i++){
$refresh_cart_array[] = $cart_product["id_web"];
}
}
$this->load->view("special_cart",array(
'refresh_cart_array' => $refresh_cart_array,
'final_cart_array' => $final_cart_array
));
} else {
$this->load->view("special_cart",array(
'refresh_cart_array' => NULL,
'final_cart_array' => NULL
));
}
}
}
I've tried every possible solution found on internet - none of them work....
I hope you understand my problem but in case you need some further explanation please ask me. Can anyone help?
Looks like the model you're trying to load wants to connect to the db, but the database driver is not available. If you use database queries in your application, why don't you load the database driver automatically?
Just insert "database" in the "libraries" array in application/config/autoload.php file. Don't forget to insert your database credentials into application/config/database.php.
$autoload['libraries'] = array('database');
If you need database connection just in one single model, load it before trying to access database library.
$this->load->database();
Try loading the model stating the module name as follows
$this->load->model('module_name/productmodel');
Class Models extends MX_Loader{
function getUser($username){
$sql="SELECT * FROM user WHERE username = ? ";
return $this->db->query($sql,array($username))->row();
}
}
you must using extends MX_Loader because i don't know if using CI_Model the database core cant be load in Codeigniter,,,
Try to use extend MX_Controller class (not CI_Contoller like you are doing atm)
Based on what you have wrote in comment above, I figured that you tried to create new instance of DB in module (based on chrises comment).
Do it on constuctor of Special_cart
So update current construct to be like
public function __construct()
{
parent::__construct();
$this->load->database('default');
}
(I'm writing this from top of my head, so check the methods)
Now for sure db driver should be available in your models.
Regarding issue with HMVC I dont think there are any. I'm using HMVC for a while now, and I found no problems in it (working with databases)
I had the same problem and mistake. I missed to extend controllers to MX_Controller. So the solution would be to change CI_Controller to MX_Controller like this:
class Special_cart extends MX_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('productmodel');
$this->load->model('stockmodel');
}
public function index()
{
if ($this->session->userdata('cart'))
{
# get product id's and each quantity
$cart_product_list = array_count_values($this->session->userdata('cart'));
# get list of product_id
$product_list = array_keys($cart_product_list);
# get product details
$cart_products = $this->productmodel->cart_get_products_details($product_list);
$final_cart_array = array();
foreach($cart_products as $cart_product){
$product_stock = $this->stockmodel->view_product_stock($cart_product["id"]);
if(empty($product_stock) || $product_stock["UNITS"]<=0)
$cart_product["UNITS"] = 0;
else{
if($cart_product_list[$cart_product["id_web"]]>$product_stock["UNITS"])
$cart_product["UNITS"] = $product_stock["UNITS"];
else{
$cart_product["UNITS"] = $cart_product_list[$cart_product["id_web"]];
}
}
$final_cart_array[] = $cart_product;
}
$refresh_cart_array = array();
foreach($final_cart_array as $cart_product){
for($i=1;$i<=$cart_product["UNITS"];$i++){
$refresh_cart_array[] = $cart_product["id_web"];
}
}
$this->load->view("special_cart",array(
'refresh_cart_array' => $refresh_cart_array,
'final_cart_array' => $final_cart_array
));
} else {
$this->load->view("special_cart",array(
'refresh_cart_array' => NULL,
'final_cart_array' => NULL
));
}
}
}
this is also explained in the documentation
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/
, here the quote:
Notes:
To use HMVC functionality, such as Modules::run(), controllers must
extend the MX_Controller class. To use Modular Separation only,
without HMVC, controllers will extend the CodeIgniter Controller
class. You must use PHP5 style constructors in your controllers. ie:
<?php
class Xyz extends MX_Controller
{
function __construct()
{
parent::__construct();
}
}