CodeIgniter HMVC data not passing from one function to another - php

i am passing function _homepage to index but it does not pass the $data['articles'] with it.
can any one help me to solve this?
this code is updated
public function index(){
$mydata = array();
$this->mydata['menu'] = $this->Mdl_page->get_nested();
$this->mydata['page'] = $this->Mdl_page->get_by(array('slug' => (string) $this->uri->segment(1)), TRUE);
count($this->mydata['page']) || show_404(current_url());
//fetch page data
$method = '_' . $this->mydata['page']->template;
if (method_exists($this, $method)) {
$this->$method();
}
else {
log_message('error', 'Could not load template ' . $method .' in file ' . __FILE__ . ' at line ' . __LINE__);
show_error('Could not load template ' . $method);
}
$this->mydata['subview'] = $data['page']->template;
//dump($data);
$this->load->view('_main_layout', $this->mydata);
}
private function _page(){
dump('Welcome from the page template');
}
private function _homepage(){
$this->load->model('admin/Mdl_Articles');
$this->db->limit(6);
$this->mydata['articles'] = $this->Mdl_Articles->get();
//dump($data['articles']);
}
private function _news_archive(){
dump('Welcome from the newspage template');
}

You should instead create a private array property
private mydata = array();
In your _homepage method, contents should be:
private function _homepage(){
// ...
// target your class scope property
$this->mydata['articles'] = $this->Mdl_Articles->get();
and change your all $data variable to $this->mydata in index method and pass it to the view like this:
$this->load->view('_main_layout', $this->mydata);

Related

Accessing an Array Variable From One Function in Another Function Within the Same Class

I have three functions within one class.
The function listUpdates() is supposed to return $this->authors;
How can I access this value in another function within the same class?
I'm attempting to access it in the function get($id), but it keeps appearing as null, however, when I var_dump it in listUpdates(), it appears without any issue.
class AuthorInformation implements ObjectStore
{
public $authors;
function path($arr, $path) {
preg_match_all("/\['(.*?)'\]/", $path, $rgMatches);
$rgResult = $arr;
foreach($rgMatches[1] as $sPath)
{
$rgResult=$rgResult[$sPath];
}
return $rgResult;
}
//get the list of author updates
public function listUpdates($url, $station, $daysOld)
{
// get the user params
$this->url = $url;
//var_dump("this is the url : " . $url . "<br/>");
$this->station = $station;
$this->daysOld = $daysOld;
curl_init("");
$wsUrl = $this->url . 'station_id=' . $this->station . '&days_changed=' . $this->daysOld . '&format=json';
//curl stuff
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$wsUrl);
$result=curl_exec($ch);
curl_close($ch);
$author_updates = json_decode($result, true);
$root = "['response']['userprofiles']";
$start = $this->path($author_updates, $root);
//$authors = [];
$this->authors = [];
foreach ($start as $author)
{
print $author['user_id'] . "<br>";
$this->authors[$author['user_id']] = $author;
// get the sharepoint author by this id
}
//var_dump($this->authors);
return $this->authors;
}
//get a single author, based on their user_id
public function get($id)
{
$this->id = $id;
var_dump("this is the user_id variable passed: ". $id);
$this->authors = $authors;
var_dump("<br/> this is the authors from listUpdates: " . $authors);
}
}
public function get($id)
{
$this->id = $id;
var_dump("this is the user_id variable passed: ". $id);
$this->authors = $authors;
var_dump("<br/> this is the authors from listUpdates: " . $authors);
}
What you're actually doing in get() is setting $this->authors to the (as yet undefined) $authors variable. You probably want to replace that line with
$authors = $this->authors;
or just use $this->authors directly, rather than assigning it to a variable.
You use $this to access properties and methods if the function is within the same class. If it is a static function you can use self:: or static::.
For example:
<?php
class Car
{
private $name = 'Ford';
public function getName()
{
return $this->name;
}
public function getOutput()
{
return 'The car name is ' . $this->getName() . '.';
}
}
?>
Make sure you are setting your properties too.

PHP: Get the name of the calling function?

Is there a way to get the name of the calling function in PHP?
In the following code I am using the name of the calling function as part of an event name. I would like to modify the getEventName() function so that it can automatically determine the name of the calling method. Is there a php function that does this?
class foo() {
public function bar() {
$eventName = $this->getEventName(__FUNCTION__);
// ... do something with the event name here
}
public function baz() {
$eventName = $this->getEventName(__FUNCTION__);
// ... do something with the event name here
}
protected function getEventName($functionName) {
return get_class($this) . '.' . $functionName;
}
}
Have a look at the output of debug_backtrace().
if you want to know the function that called whatever function you are currently in, you can define something like:
<?php
/**
* Returns the calling function through a backtrace
*/
function get_calling_function() {
// a function x has called a function y which called this
// see stackoverflow.com/questions/190421
$caller = debug_backtrace();
$caller = $caller[2];
$r = $caller['function'] . '()';
if (isset($caller['class'])) {
$r .= ' in ' . $caller['class'];
}
if (isset($caller['object'])) {
$r .= ' (' . get_class($caller['object']) . ')';
}
return $r;
}
?>

extending class and protected data

im trying to create a class to manage widgets. I have problems with a protected data in parent class:
Widget.php
/** Parent class **/
class Widget{
protected $html =""; //formated html data
// method to load views in {system_path}/widgets/{widget_name}/views/
protected function LoadView($filename){
if(!empty($filename) && is_string($filename)){
$output = "";
$dir = WIDGET_PATH . "views" . DS . $filename;
ob_start();
include($dir);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
return NULL;
}
//method to render formated html data
public function Render(){
if(isset($this->html) && !empty($this->html)){
return $this->html;
}
return NULL;
}
//static method to load a Widget
public static function Load($widgetName){
if(!empty($widgetName) && is_string($widgetName)){
$widgetName = strtolower($widgetName);
if(file_exists(WIDGET_PATH . $widgetName . DS . $widgetName . ".php")){
include_once(WIDGET_PATH . $widgetName . DS . $widgetName . ".php");
if(class_exists($widgetName."_Widget")){
$class = $widgetName."_Widget";
return new $class();
}
}
}
return FALSE;
}
}
/widgets/socialbar.php
/** SocialBar Widget **/
class Socialbar_Widget extends Widget
{
public function __construct(){
$this->html = "demo"; // test to see if it works
}
}
index.php
/*load class files, etc */
$Social = Widget::Load("socialbar"); //works, perfectly loads Socialbar_Widget()
var_dump($social); // works : object(Socialbar_Widget)[29] protected html = 'demo' ......
$Social->Render(); // throws Fatal error: Using $this when not in object context
To extend a variable inside parent class should i use "public"? Or what i mistake.
Thanks for help guys.
Your class name is class Socialbar_Widget,
Your are calling it in lower case
$Social = Widget::Load("socialbar")
and in load method you are doing strtolower($widgetName).
Check class file name.php. Load function may have returning false.

Render a view in PHP

I am writing my own MVC framework and has come to the view renderer. I am setting vars in my controller to a View object and then access vars by echo $this->myvar in the .phtml script.
In my default.phtml I call the method $this->content() to output the viewscript.
This is the way I do it now. Is this a proper way to do that?
class View extends Object {
protected $_front;
public function __construct(Front $front) {
$this->_front = $front;
}
public function render() {
ob_start();
require APPLICATION_PATH . '/layouts/default.phtml' ;
ob_end_flush();
}
public function content() {
require APPLICATION_PATH . '/views/' . $this->_front->getControllerName() . '/' . $this->_front->getActionName() . '.phtml' ;
}
}
Example of a simple view class. Really similar to yours and David Ericsson's.
<?php
/**
* View-specific wrapper.
* Limits the accessible scope available to templates.
*/
class View{
/**
* Template being rendered.
*/
protected $template = null;
/**
* Initialize a new view context.
*/
public function __construct($template) {
$this->template = $template;
}
/**
* Safely escape/encode the provided data.
*/
public function h($data) {
return htmlspecialchars((string) $data, ENT_QUOTES, 'UTF-8');
}
/**
* Render the template, returning it's content.
* #param array $data Data made available to the view.
* #return string The rendered template.
*/
public function render(Array $data) {
extract($data);
ob_start();
include( APP_PATH . DIRECTORY_SEPARATOR . $this->template);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
}
?>
Functions defined in the class will be accessible within the view like this:
<?php echo $this->h('Hello World'); ?>
Here's an example of how i did it :
<?php
class View
{
private $data = array();
private $render = FALSE;
public function __construct($template)
{
try {
$file = ROOT . '/templates/' . strtolower($template) . '.php';
if (file_exists($file)) {
$this->render = $file;
} else {
throw new customException('Template ' . $template . ' not found!');
}
}
catch (customException $e) {
echo $e->errorMessage();
}
}
public function assign($variable, $value)
{
$this->data[$variable] = $value;
}
public function __destruct()
{
extract($this->data);
include($this->render);
}
}
?>
I use the assign function from out my controller to assign variables, and in the destructor i extract that array to make them local variables in the view.
Feel free to use this if you want, i hope it gives you an idea on how you can do it
Here's a full example :
class Something extends Controller
{
public function index ()
{
$view = new view('templatefile');
$view->assign('variablename', 'variable content');
}
}
And in your view file :
<?php echo $variablename; ?>

PHP Action each function preforms

I have the following situation.
I have a class with a lot of functions. Each function starts with executing the same method. Is there a way that I can like implement this method into the function so that it is executed automatically?
Here is an example:
class test
{
static function_1($param) {some_method($param); other stuff....}
static function_2($param) {some_method($param); other stuff then function 1....}
static function_3($param) {some_method($param); other stuff then function 1 and function 2....}
}
So is there a way to execute some_method(); automaticly without declaring it in each function?
Thanks in advance!
Whole code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* The Assets Library
*
* This class let's you add assets (javascripts, stylesheets and images) way easier..
*/
class Assets {
private $css_url;
private $js_url;
private $img_url;
public function __construct()
{
$CI =& get_instance();
$CI->config->load('assets');
$asset_url = base_url() . $CI->config->item('assets_dir');
$this->css_url = $asset_url . $CI->config->item('css_dir_name');
$this->js_url = $asset_url . $CI->config->item('js_dir_name');
$this->img_url = $asset_url . $CI->config->item('img_dir_name');
}
// Returns the css html link
public function css_html_link($filename)
{
// Check whether or not a filetype was given
$filename = $this->_add_filetype($filename, 'css');
$link = '<link type="text/css" rel="stylesheet" href="' . $this->css_url . $filename . '" />';
return $link;
}
// Returns the css link
public function css_link($filename)
{
$filename = $this->_add_filetype($filename, 'css');
return $this->css_url . $filename;
}
// Returns the js html link
public function js_html_link($filename)
{
$filename = $this->_add_filetype($filename, 'js');
$script = '<script type="text/javascript" src="' . $this->js_url . $filename . '"></script>';
return $script;
}
// Return the js link
public function js_link($filename)
{
$filename = $this->_add_filetype($filename, 'js');
return $this->js_url . $filename;
}
// Returns the image html tag
public function img_html_link($filename, $rel = NULL)
{
// Get the filename without the filetype
$alt_text = substr($filename, 0, strpos($filename, '.')+1);
$alt_text = 'alt="'.$alt_text.'"';
// If relation is giving, use it
$img_rel = ($rel !== FALSE) ? 'rel="' . $rel . '"' : '';
$image = '<img src="' . $this->img_url . $filename . '" '.$rel.' ' . $alt_text . '/>';
return $image;
}
// Return the image link
public function img_link($filename)
{
return $this->img_url . $filename;
}
// Check whether or not a filetype was specified in $file, if not, it will be added
private function _add_filetype($file, $type)
{
if(strpos($file, '.' . $type) === FALSE)
{
$file = $file . '.' . $type;
}
return $file;
}
}
/* End of file assets.php */
/* Location: ./application/libraries/assets.php */
every time you initiate the class, it calls the __construct() function, or in PHP 4 (I hope you are not using php 4) it uses the function with the same name as the class
If you do this, it should work for every initiate of the class:
function __construct($param){
some_method($param);
}
if you call multiple functions in the same initiation of the class, you could do this:
var $param;
function __construct($param){
$this->param = $param;
}
function doMethod(){
some_method($this->param);
}
function function_1()
{
$this->doMethod();
}
Calling the class multiple times, with different params. Perhaps try this approach:
function __call($function, $param){
some_method($param);
switch ($function){
case 'function1':
$this->function1($param);
break;
/// etc..
}
}
I'm afraid that in this case the answer is 'no'.
You're not 'declaring' some_method() each time, you are calling it. If you don't call it, it can't run, so you have to call it each time.
Cut & paste.....
Why not paste your actual code here, some refactoring may help.
Edit after seeing actual code
I can't see the problem with your existing code. It is clear and you will know what it does in a year's time. I would keep it as it is. The answer you accepted will work, but it is obfuscating your code. You will have problems working out what you did and why you did it in when you come back to maintain your code in the future.
You could create a class containing an instance of the class test (composition) and implement its __call magic method. Something akin to:
class testWrapper
{
private $test;
function __construct()
{
$this->test = new Test();
}
function __call($name, $args)
{
call_user_func_array(array($this->test, 'some_method'), $args);
call_user_func_array(array($this->test, $name), $args);
}
}
You then call methods from the test class on the instance object of testWrapper.
You can further refine the logic in the __call method to only call some_method() based on the passed-in method name, etc.

Categories