How can I avoid repeating variables? - php

In the following code, I have to use $module = $this->uri->segment(4);, table = "omc_".$module; and $id = $this->uri->segment(5); in every function in this class.
How can I avoiding this repetition?
Thanks in advance.
class Admin extends Shop_Admin_Controller {
function Admin(){
parent::Shop_Admin_Controller();
}
function changeStatus(){
$module = $this->uri->segment(4);
$table = "omc_".$module;
$id = $this->uri->segment(5);
if($id && $table){
$this->MKaimonokago->changeStatus($table,$id);
}
flashMsg('success',$this->lang->line('kaimonokago_status_changed'));
redirect("$module/admin/index/","refresh");
}
.................
.................

You could simply add then as instance (i.e.: class level) variables with the appropriate visibility (protected or private) and then initialise them within your constructor.
By doing this you wouldn't need to initialise them within each method, and would still have a more convenient naming regime.
For example:
class Admin extends Shop_Admin_Controller {
private $module;
private $table;
private $id;
public function __construct() {
parent::__construct();
// Initialise uri class here, unless this is done
// in the parent constructor.
$this->module = $this->uri->segment(4);
$this->table = "omc_".$module;
$this->id = $this->uri->segment(5);
}
public function changeStatus() {
if($this->id && $this->table) {
...
}
}
}
Incidentally, I'd also recommend setting the appropriate visibility on your methods, unless of course you're targeting PHP 4, in which case replace the "private" with "var" in the above example and remove the visibility properties from the methods.

How about setting them in the constructor?
function Admin(){
parent::Shop_Admin_Controller();
$this->module = $this->uri->segment(4);
$this->table = "omc_" . $this->module;
$this->id = $this->uri->segment(5);
}
They can then be used as e.g. $this->module in the other functions in your class.
This of course presumes that you don't have properties with those names in the parent class. If you do, you use different names.

Maybe set them as protected attributes in your constructor?
class Admin
{
protected $_module;
protected $_table;
protected $_id;
public function __construct()
{
// do something that initializes $this->uri;
$this->_module = $this->uri->segment(4);
$this->_table = 'omc_' . $module;
$this->_id = $this->uri->segment(5);
}
}

Related

Accessing variables from constructors in static methods

I have a class with methods, some of these methods use the same variable across board - "$company_id". Now, I don't want to explicitly define what is contained in $company_id for every method. I want to define it once in a constructor and then reference it in my methods. Please how do I do this? This is how it looks currently.
public function __construct(){
//what should I do here?
}
public static function getItemLimit(){
$company_id = Auth::user()->company_id;
$item_limit = Company::where('id', $company_id)->count();
return $item_limit;
}
public static function currentItemCount(){
$company_id = Auth::user()->company_id;
$item_count = Item::where('company_id', $company_id)->count();
return $item_count;
}
Try this Use Company_Id instead of $abcVar
class Abc{
public static $abcVar = '';
public function __construct()
{
self::$abcVar = 11;
}
public static function getItemLimit()
{
echo self::$abcVar;
exit;
}
}
$obj = new Abc();
Abc::getItemLimit();

Inheritance in PHP - Creating child instance and calling parent method

I have something like this:
class MyParent {
protected static $object;
protected static $db_fields;
public function delete() {
// delete stuff
}
public static function find_by_id($id = 0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM " . static::$table_name . " WHERE id=" . $database -> escape_value($id) . " LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql = "") {
global $database;
// Do Query
$result_set = $database -> query($sql);
// Get Results
$object_array = array();
while ($row = $database -> fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record) {
$object = self::$object;
foreach ($record as $attribute => $value) {
if (self::has_attribute($attribute)) {
$object -> $attribute = $value;
}
}
return $object;
}
}
class TheChild extends MyParent {
protected static $db_fields = array('id', 'name');
protected static $table_name = "my_table";
function __construct() {
self::$object = new TheChild;
}
}
$child= TheChild::find_by_id($_GET['id']);
$child->delete();
I get this: Call to undefined method stdClass::delete() referring to the last line above. What step am I missing for proper inheritance?
You never actually instanciate the TheChild class, which should be done by
$var = new TheChild();
except in TheChild constructor itself.
So, the static $object field is never affected (at least in your example), so affecting a field to it (the line $object -> $attribute = $value; ) causes the creation of an stdClass object, as demonstrated in this interactive PHP shell session:
php > class Z { public static $object; }
php > Z::$object->toto = 5;
PHP Warning: Creating default object from empty value in php shell code on line 1
php > var_dump(Z::$object);
object(stdClass)#1 (1) {
["toto"]=>
int(5)
}
This object does not have a delete method.
And as said before, actually creating a TheChild instance will result in an infinite recursion.
What you want to do is this, probably:
class TheChild extends MyParent {
protected static $db_fields = array('id', 'name');
protected static $table_name = "my_table";
function __construct() {
self::$object = $this;
}
}
Edit: Your updated code shows a COMPLETE different Example:
class MyParent {
protected static $object;
public function delete() {
// delete stuff
}
}
class TheChild extends MyParent {
function __construct() {
self::$object = new TheChild;
}
}
$child = new TheChild;
$child->delete();
Calling "Child's" Constructor from within "Child's" Constructor will result in an infinite loop:
function __construct() {
self::$object = new TheChild; // will trigger __construct on the child, which in turn will create a new child, and so on.
}
Maybe - i dont know what you try to achieve - you are looking for:
function __construct() {
self::$object = new MyParent;
}
ALSO note, that the :: Notation is not just a different Version for -> - it is completely different. One is a Static access, the other is a access on an actual object instance!

Cannot use right the inheritance in PHP class

I have this parent class in PHP:
class parentClass{
public $table;
public function __construct(){
$this->table = "my_parent_table";
}
public function getName($id) {
$strQuery = "SELECT name FROM $this->table WHERE id=$id";
$result = mysql_query($strQuery);
if ($result) {
$row = mysql_fetch_object($result);
if ($row) {
return $row->name;
} else {
return false;
}
} else {
return false;
}
}
}
And I have also another class with inherits this one:
class childClass extends parentClass{
public $table;
public function __construct(){
$this->table = "my_child_table";
}
}
Then in another file I am doing:
$myObj = new childClass();
$name = $myObj->getName('1');
The problem now is that the getName function has a null table, so the variable $this->table is null, while I want it to be ""my_child_table" as long as I have a childClass object.
Does anyone know what I am doing wrong?
Thanks in advance
Not sure, but this look tricky:
class childClass extends parentClass{
public $table;
The parentClass already defines a $table, so it's likely that redeclaring it inside the child class will clobber the parent's version. You have to remove the declaration here. Also, public visibility doesn't really encapsulate the state very well; use protected in the parent instead.
public function __construct()
{
You should add parent::__construct() here (unless parent only sets $this->table, but even then it's good to add)
$this->table = "my_child_table";
}
}

Polymorphism/Resource loader with Zend

I've never worked before with polymorphism. I just heard about it when this question came up.
I have a little backend with 2 permissions. Admin/Normal User. Depending on the permission, i want to display a different navigation, less or more options on the forms etc. But i don't want to create a form for each permission but rather disable the elements i don't need etc.
How would i go with that?
At the moment, i'm using something like that: (Which isn't really polymorphism)
<?php
class My_Resources_ResourceLoader extends Zend_Application_Resource_ResourceAbstract {
public $templateForm = null;
public $customerForm = null;
function init() {
$permission = 'admind';
if($permission == 'admin') {
$this->templateForm = new Application_Form_newTemplate;
} else {
$form = new Application_Form_newTemplate;
$form->removeElement('newTemplate_customer');
$this->templateForm = $form;
}
return $this;
}
}
And in my controller e.g.
<?php
$bootstrap = $this->getInvokeArg('bootstrap');
$xx = $bootstrap->getResource('ResourceLoader');
$this->view->test = $xx->templateForm;
The roles never gonna change. This will probably be okay but isn't the very best solution. What would be a better approach to this?
I've thrown away the approach above and now use real polymorphism like this:
at Application/Model got an interface like:
And 2 Classes like:
<?php
class Application_Model_TemplateUser implements Application_Model_TemplateInterface {
private $table = null;
private $row = null;
private $id = null;
private $formValues = null;
function __construct() {}
public function exist() {}
public function save() {}
public function getCustomerId($name) {}
public function update() {}
public function getForm() {
$form = new Application_Form_newTemplate;
$form->removeElement('newTemplate_customer');
return $form;
}
}
And
<?php
class Application_Model_TemplateAdmin implements Application_Model_TemplateInterface {
private $table = null;
private $row = null;
private $id = null;
private $formValues = null;
function __construct() {}
public function exist() {}
public function save() {}
public function getCustomerId($name) {}
public function update() {}
public function getForm() {
return new Application_Form_NewTemplate();
}
}
In my Controller i do:
<?php
$permission = 'User'; //TODO: Get from Session
$class = 'Application_Model_Template' . $permission;
$xx = new $class;
$form = $xx->getForm();
$this->view->test = $form;
This are just examples. But i think like that I'm really on a better way. Maybe i'm going to use abstract classes since i'm using Zend_Db-Table_Row, which is always the same for updating a row, so it would make more sense using a abstract class instead of an interface.
Nice article about Polymorphism in PHP: http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/

help with accessing variables inside of my class

Hmmm, so how is this done?
I have a class
class Themes extends Access
{
public $theme_name;
public $theme_by;
public $theme_by_email;
public $theme_by_website;
public $theme_description;
public $theme_thumb;
public $theme_source;
public $theme_uploaded_on;
public function __construct()
{
parent::__construct();
//$this->get_theme();
}
public function get_theme()
{
$sql = "SELECT *
FROM `user_themes`
WHERE `user_id` = " . $this->session->get('user_id');
if($this->db->row_count($sql))
{
$result = $this->db->fetch_row_assoc($sql);
$this->$theme_name = $result['theme_name'];
$theme_by = $result['theme_by'];
$theme_by_email = $result['theme_by_email'];
$theme_by_website = $result['theme_by_website'];
$theme_description = $result['theme_description'];
$theme_source = $result['theme_source'];
$theme_uploaded_on = $result['theme_uploaded_on'];
}else{
die('no results');
}
}
}
How can I access these variables and their contents outside of the class?
in my PHP page I have
$theme = new Themes();
I tried to access my variable using
$theme->them_name but I get an undefined error
but don't really know how I can access the variable...
With your current setup, all you have to do is call:
$theme->theme_name;
$theme->theme_by;
etc
However it is generally not good practice to make instance variables public, rather make them private and make mutator methods.
An example would be:
private $theme_name;
public function getThemeName(){
return $this->theme_name;
}
public function setThemeName($theme){
$this->theme_name = $theme;
}
$this->theme_name = $result['theme_name'];
$this->theme_by = $result['theme_by'];
Note on $this prepended.
After that you can access the data using $theme->theme_name etc

Categories