PHP Action each function preforms - php

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.

Related

Using setParams with include

I'm trying to edit a template system so where I can use params such as [title] and it'll show my title in the included page. But I also want to be able to use php code inside of it and be able to execute that code. But I am having difficult getting them both to work at the same time.
I have tried to use include instead of file_get_Contents but when I use include, the params no longer work. However when I use file_get_contents the php doesnt work, and doesnt show.
My code:
class Template {
public function __construct($directory){
$this->dir = $directory;
}
public function setPage($pageName){
$this->directory = 'lib/' . $this->dir . '/' . $pageName . '.php';
if(file_exists($this->directory)) {
$Content = file_get_contents($this->directory);
}
}
public function newParam($trans, $val){
$this->param['[*' . $trans . '*]'] = $val;
}
public function setParams($element){
$element = str_replace(array_keys($this->param), array_values($this->param), $element);
return $element;
}
public function Create(){
die($this->setParams($Content));
}
}
Hope someone can help. Thanks

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;
}
?>

Access variables within a class in numerous functions

If, for example, I have a class called images in which I query the database to get a image src, image name, and some other strings:
$sql = Nemesis::select("profile_picture_thumb, profile_picture_large, facebook_id", "users", "id = '{$_SESSION[user_id]}'");
list($profile_picture_thumb, $profile_picture_large, $facebook_id) = $sql->fetch_row();
Is there a way where I can, maybe in __construct set these as a $var in which I can access them in numerous functions within the class? Furthermore, are there any performance benefits in doing this aside from conciseness? I would assume since your essentially querying the database once rather than under numerous function and setting it as a "global" within the class performance would increase... or no?
More explicit:
class Images
{
var $main_prepend = 'm_';
var $thumb_prepend = 't_';
var $default_ext = 'jpg';
var $cropfactor;
private $profile_picture_thumb;
private $profile_picture_large;
private $facebook_id;
public function __construct()
{
$sql = Nemesis::select("profile_picture_thumb, profile_picture_large, facebook_id", "users", "id = '{$_SESSION[user_id]}'");
list($profile_picture_thumb, $profile_picture_large, $facebook_id) = $sql->fetch_row();
$this->profile_picture_thumb = $profile_picture_thumb;
$this->profile_picture_large = $profile_picture_large;
$this->facebook_id = $facebook_id;
}
public function profilePic($show = true, $delete = false)
{
if ($show) {
echo '<script type="text/javascript">$(function() { $("#profile-picture").tipsy({fade: true}); });</script>';
if (is_file(ROOT . $this->profile_picture_thumb)) {
echo '<img src="' . reduce_double_slashes('../' . $this->profile_picture_thumb) . '" id="profile-picture" class="profile-picture" title="Your Profile Picture">';
} elseif (!empty($this->facebook_id)) {
// if there is no profile picture set, and user has listed fb profile picture, get profile picture
$fb_p_thumb = "http://graph.facebook.com/{$facebook_id}/picture";
$fb_p_large = "http://graph.facebook.com/{$facebook_id}/picture?type=large";
echo '<img src="' . $fb_p_thumb . '" id="profile-picture" class="profile-picture" title="Facebook Profile Picture">';
} else {
echo '<img src="images/50x50_placeholder.gif" id="profile-picture" class="profile-picture" title="Click to add profile picture">';
}
}
if ($delete) {
if (is_file(ROOT . $this->profile_picture_thumb) || is_file(ROOT . $this->profile_picture_larg)) {
if (!unlink(ROOT . $this->profile_picture_thumb) && !unlink(ROOT . $this->profile_picture_larg)) {
$msg->add('e', "Could not delete user profile picture!");
}
} else {
$msg->add('e', "Files not found in directory.");
}
}
}
public function profilePicExists($msg = true, $delete = false)
{
if ($msg) {
if (is_file(ROOT . $this->profile_picture_thumb)) {
echo '<div class="ec-messages messages-success">Profile picture exists or was added! It may be required to refresh the page to view changes.</div>';
}
}
if ($delete) {
if (is_file(ROOT . $this->profile_picture_thumb)) {
echo '<input name="doDelete" type="submit" class="btn btn-warning" id="doDelete2" value="Remove Profile Picture">';
}
}
}
Does not work.
class Images {
private $src;
private $name;
public function __construct($src, $name) {
$this->src = $src;
$this->name = $name;
}
public function get_src() {
return $this->src;
}
public function get_name() {
return $this->name;
}
}
$instance = new Images('image.jpg', 'Cute Duck');
echo $instance->get_src();
echo '<br>';
echo $instance->get_name();
Here in your Images class you store the name and the source in two class variables, that you can set in the constructor when you create a new Image class. You can get the values by the two getter function get_name() and get_src().
You could also set these variables to public, sou you could access them directly:
class Images {
public $src;
public $name;
}
$instance = new Images();
$instance->src = 'image.jpg';
$instance->name = 'Cute Duck';
echo $instance->src;
echo '<br>';
echo $instance->name;
You could store and run queries like this:
class Images {
private $query;
private $result;
public function __construct($query) {
$this->query = $query;
//run query than store it in $this->result;
}
public function get_result() {
return $this->result;
}
}
$instance = new Images('SELECT * FROM stuff');
echo $instance->get_result();
This way you can pass the SQL statement in the constructor, where you do your job and store the result. You can access the result through the getter or in any other function that is in the class.
Note that this is not a persistent solution, after you reload the page (or go to another) that use the class in the server side, it starts from the beginning. But you can structure your code and put common functions that you use a lot into the class, so you don't have to duplicate code.
For example you can write an Image class where you can store the name, size, file extension, source, etc. You can give these in the constructor when you create the class or set them via setters or directly if the class variables are public.
After you set these, you can use all of the functions that are in the class. For example you can write a function that copy the image, one that resize or rename it, one that delete it. Any time you need to work with a concrete image you just create a class instance and call the needed functions.
If you want to perform more operations, for example clone an image, than delete the original, or resize the image then clone it, you don't have to set all the settings again for your image because they are stored in the class and the functions have access to it.

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; ?>

Categories