Trying to crate objects dynamically for a plug in system (work in progress)
heres my code using $this->module->load_module('test'); to use the method that creates the dynamic objects. Following code is the function that loads the class's and makes use of an auto loader, i have checked that its getting the correct file etc.
<?php
class BaseModule {
function __construct() {
}
function load_module($module){
echo 'Module = '.$module.'<br />';
$object_name = $module . "Controller";
$this->$$module = new $object_name();
}
}
Here is a test module that it would load when invoking $this->module->load_module('test'); and it creates the object outputting the test strings via echo statements. Heres the code for the test module that was constructed. Which should cause no problems as there is not really a solution but just an output string, but posted any way.
<?php
class testController {
function __construct() {
echo 'test controller from modules <br />';
}
}
However when running the page i am getting some errors can any one help out?
Notice: Undefined variable: test in
/Applications/MAMP/htdocs/tealtique/application/modules/BaseModule.php on line 11
Fatal error: Cannot access empty property in
/Applications/MAMP/htdocs/tealtique/application/modules/BaseModule.php on line 11
Related
I have a project on PHP and I have to use a DOTNET DLL which was written on C# . I have to call different functions of the same object in two different PHP pages. In the first page it works but I get this error in the second page. Can you please help me? These are example ;
DOTNET DLL :
namespace FirstDotNet
{
[ComVisible(true)]
public class Class1
{
public string SampleFunction()
{
return "hello";
}
}
}
PHP Class File animals.php
class Animal{
var $abc;
public function do_it(){
$this->abc = new DOTNET("FirstDotNet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxx", "FirstDotNet.Class1");
}
}
First PHP FILE a.php (this works, output is 'Hello')
require_once("animals.php");
session_start();
$first_animal = new Animal();
$_SESSION["animal"] = $first_animal;
$first_animal->do_it();
echo $first_animal->abc->SampleFunction();
Second PHP FILE b.php (this doesnt work, output is Fatal error: Call to undefined method dotnet::SampleFunction())
require_once("animals.php");
session_start();
$animal2 = $_SESSION["animal"];
echo $animal2->abc->SampleFunction();
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 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!
In CodeIgniter I'm try to made header with code from DB, my controller code:
public function index()
{
$this->load->model('main_model');
$data['result'] = $this->main_model->get_tipsters();
$this->load->view('template/header_view',$data);
}
And header_view:
<?php foreach($result->result() as $row): ?>
<div id="tipster"><img src="<?=$row->photo;?>" /><br /><?=$row->name;?></div>
<?php endforeach; ?>
Header work's only It self view file, but not In others pages.
I Including header like this in controllers:
$this->load->view('template/header_view');
$this->load->view("/bets/index",$data);
$this->load->view('template/footer_view');
Getting this error
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: result
Filename: template/header_view.php
Line Number: 14
Fatal error: Call to a member function result() on a non-object in /home/user/domains/test.com/public_html/application/views/template/header_view.php on line 14
Line 14 is foreach, I have copied early.
Since your header view file is always expecting $result, you'll need to provide it for all your controller methods:
$this->load->model('main_model');
$data['result'] = $this->main_model->get_tipsters();
$data['main'] = $this->main_model->get_main_data(); //example
$this->load->view('template/header_view',$data);
$this->load->view("bets/index",$data);
$this->load->view('template/footer_view');
This can become cumbersome, so consider creating a MY_Controller file that extends CI_Controller - more about that here.
You can make a function in your Common_model
for fecthing result on your header file.
and directly get result from that function by calling it in a view file.
common_model.php
function your_function()
{
// code for fetching data for header
/// return your result here
}
call directly this function in a view file as
$rs = $this->Common_model->your_function();
Note: common_model is load by default .if disable then you need to load model in a view file.
Best way to load CI object on view element file(header_view) and load and call model method with CI object
$CI = & get_instance()
$CI->load->model('main_model');
$result = $CI->main_model->get_tipsters();
<?php foreach($result->result() as $row): ?>
<div id="tipster"><img src="<?=$row->photo;?>" /><br /><?=$row->name;?></div>
<?php endforeach; ?>
and remove code from controller
I have just created a class to control my php application, and I have one big problem ( I use 2 days for thinking and searching about it but can't find any solutions). My class contains a method named register(), which load scripts into pages. My class is:
class Apps
{
protected $_remember; // remember something
public function register($appName)
{
include "$appName.php"; //include this php script into other pages
}
public function set($value)
{
$this->_remember = $value; // try to save something
}
public function watch()
{
return $this->_remember; // return what I saved
}
}
And in time.php file
$time = 'haha';
$apps->set($time);
As the title of my question , when I purely include time.php into main.php, I can use $apps->set($time) ($apps has been defined in main.php). Like this main.php:
$apps = new Apps();// create Apps object
include "time.php";
echo $apps->watch(); // **this successfully outputs 'haha'**
But when I call method register() from Apps class to include time.php , I got errors undefined variable $apps and call set method from none object for time.php (sounds like it doesn't accept $apps inside time.php to me) . My main.php is:
$apps = new Apps();// create Apps object
$apps->register('time'); // this simply include time.php into page and it has
//included but time.php doesn't accept $apps from main.php
echo $apps->watch(); // **this outputs errors as I said**
By the way , I'm not good at writing . So if you don't understand anything just ask me. I appreciate any replies. :D
If you want your second code snippet to work, replace the content of time.php with:
$time = 'haha';
$this->set($time); // instead of $apps->set($time);
since this code is included by an instance method of the Apps class, it will have access to the instance itself, $this.