Jump to content

totally stuck on a oop - passing a value from 1 class to another


ricky spires

Recommended Posts

hello.

 

i have posted something similar before and people said i should go away and learn oop. I have since done the entire Linda training on oop, watched countless videos and build a photo gallery (from the training videos) but im still stuck on this silly little thing. :(

 

so please please could some one help. thanks

 

ok, so i have 2 classes. 1 called Pages and 1 called Templates.

each page has an id for the layout it wants to use.

 

so i want to get the layoutTemps_id from the pages class and use it in a function WHERE clause to get the correct layout for that page.

 

I cant seem to pass the layoutTemps_id into my Templates class from my Pages Class ???

 

i tried using a global but couldnt get it to work.

 

ANY IDEAS ?? thanks

 

this is the Pages class function that gets all the information for each page.

 

public static function find_by_pageName($pName){
	global $database;
	$sql = "SELECT * FROM ".self::$table_name." WHERE pageName='".$database->escape_value($pName)."'";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}

 

that works just fine. it gets the $pName on the page and is different each time.

i.e

$pName = "adminHome";
$page = Pages::find_by_pageName($pName);

echo $page->id."<br />";
echo $page->layoutTemps_id.'<br/>';

 

 

so that all seems to work fine. now i want to use the $page->layoutTemps_id in my Templates class.

 

this is the class

class Templates extends Pages {

 

this is the function im trying to write. i thought that because class Templates extends Pages i could put in $page->layoutTemps_id with no problem but in stuck.

 

public static function find_layoutTemp(){

$layoutTemps_id = Pages::layoutTemps_id;

	$sql = "SELECT * FROM ".self::$table_name." WHERE id='".$database->escape_value($layoutTemps_id)."'";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}

 

this is the page where im echoing the layoutTemps_id

 

<?PHP
require_once("../includes/initialize.php");
$temp = Templates::find_layoutTemp();

echo "layoutTemp id " .$temp->id . " <br />";
echo "layoutTemp name " .$temp->name ." <br />";

 

now, i'm 100% sure there's lots wrong with my code but i'm ill be happy if someone could help.

 

thanks

rick :)

 

 

 

 

 

Link to comment
Share on other sites

Using the global keyword in a method? I'm not sure what Linda is teaching, but it seems you've kinda strayed from what OOP is all about.

 

Without seeing what data you actually want to get I can only guess exactly what you're trying to accomplish here.

 

I'm throwing together an example of what I think you want.

Link to comment
Share on other sites

Also, you seem to be using static data members, with a variable that conceptually shouldn't be static. Since (I assume) different instances of a page class will have different page layouts, the variable holding that information shouldn't be static (as that implies it never changes, and that each instance of the page class should just share 1)

 

However, as Xyph mentioned, without seeing how your classes are structured, it will be hard to give you a direction on how the relationship between the two classes should work.

Link to comment
Share on other sites

hello.

 

THANKYOU xyph and mikesta707 for helping to point me in the right direction so i can get on with my project :)

 

 

global keyword in a method?

 

im was using global $database because thats how they do it in Lynda training and i was thinking of using global $layoutTemps_id because i saw my friend doing something like that. yesterday i was moving away from that because your totally right, it's straying from what OOP is all about.

 

 

you seem to be using static data members

 

thanks. your right ill change that ;)

 

 

 

 

so, this is what im try to do. It trying to put together my own CMS with the ability to add/edit/delete the admin and fron end template.

it's the first time i have tried to put together a template system and use oop so i might have it all wrong but everyone starts some where :)

 

this is how im putting together the pages and classes.

 

1. when you go to admin/index.php it will look in the adminSettings class to find the template name

2. the template folder includes all the layouts / css / images for that template

3. the wrapper / header / top nav and footer are all set in the template.

4. depending which page they go to the template gets the layout.

so in my cases case they are going to home.php and i have called the page $pName = "adminHome".

5. the class Pages will call all the information about that page using the $pName

6. the template is using the class template to find which layout the page is using.

7. the each layout gets its content. so if you have a 2 col layout the left col will get the navigation and the right will get the main content (for example)

 

so this is how the flow goes.

admin - index - template - page - template layout - content

 

hope that makes a little sence :)

 

 

 

so this is the entire code for Pages class

 

<?PHP
require_once(LIB_PATH.DS.'database.php');

class Pages {

protected static $table_name="pages";

protected static $db_fields = array(
'id','pageName','visible','layoutElements_id','layoutPositions_id','layoutTemps_id','pageZones_id','pageCRUD_id','pageTypes_id''module_id','title','sub_title','description','about','image','created','dateMod','timeMod');


public $id;
public $visible;
public $pageName;
public $layoutElements_id;
public $layoutPositions_id;
public $layoutTemps_id;
public $pageZones_id;
public $pageCRUD_id;
public $pageTypes_id;
public $module_id;
public $title;
public $sub_title;
public $description;
public $about;
public $image;
public $created;
public $dateMod;
public $timeMod;



// "new" is a reserved word so we use "make"(or "build")
public static function make(

$id="",$pageName="",
$visible="",
$layoutElements_id="",
$layoutPositions_id="",
$layoutTemps_id="",
    $pageZones_id="",
$pageCRUD_id="",
$pageTypes_id="",
$module_id="",
	$title="",
$sub_title="",
$description="",
$about="",
$image="",
$created="",
$dateMod="",
$timeMod="") {

	if(!empty($title)) {

		$kw = new NavL3();
		$kw->id = (int)$id;
		$kw->pageName = $pageName;
		$kw->visible = (int)$visible;
		$kw->layoutElements_id = (int)$layoutElements_id;
		$kw->layoutPositions_id = (int)$layoutPositions_id;
		$kw->layoutTemps_id = (int)$layoutTemps_id;
		$kw->pageZones_id = (int)$pageZones_id;
		$kw->pageCRUD_id = (int)$pageCRUD_id;
		$kw->pageTypes_id = (int)$pageTypes_id;
		$kw->module_id = (int)$module_id;
		$kw->title = $title;
		$kw->sub_title = $sub_title;
		$kw->description = $description;
		$kw->about = $about;
		$kw->image = $image;
		$kw->created = $created;
		$kw->dateMod = $dateMod;
		$kw->timeMod = $timeMod;

		return $kw;
	}else{
		return false;
	}
} //end function make

public function find_by_pageName($pName){
	global $database;
	$sql = "SELECT * FROM ".self::$table_name." WHERE pageName='".$database->escape_value($pName)."'";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}







// Common Database Methods


public static function find_all(){
	global $database;
	$sql = "SELECT * FROM ".self::$table_name."";
	return self::find_by_sql($sql);
}

public static function find_by_id($id=0){
	global $database;
	$sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($id)." LIMIT 1";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}

public static function find_by_sql($sql){
	global $database;
	$results_set = $database->query($sql);
	$object_array = array();
	while($row = $database->fetch_array($results_set)){
		$object_array[] = self::instantiate($row);
	}
	return $object_array;
}

public static function count_all(){
	global $database;
	$sql = "SELECT COUNT(*) FROM ".self::$table_name;
	$results_set = $database->query($sql);
	$row = $database->fetch_array($results_set);
	return array_shift($row);
}

public static function instantiate($result){
	$object = new self;
	foreach($result as $attribute => $value){
		if($object->has_attribute($attribute)){
			$object->$attribute = $value;
		}
	}
	return $object;
}

private function has_attribute($attribute){
	$object_vars = $this->attributes();
	return array_key_exists($attribute, $object_vars);
}


protected function attributes(){
	$attributes = array();
	foreach(self::$db_fields as $field){
		if(property_exists($this, $field)){
			$attributes[$field] = $this->$field;
		}
	}
	return $attributes;
}

protected function sanitized_attributes(){
	global $database;
	$clean_attributes = array();
	foreach($this->attributes() as $key => $value){
		$clean_attributes[$key] = $database->escape_value($value);
	}
	return $clean_attributes;
}

public function save(){
	return !empty($this->id) ? $this->update() : $this->create();
}

public function create(){
	global $database;
	$attributes = $this->sanitized_attributes();
	$sql = "INSERT INTO ".self::$table_name." (";
	$sql .= join(", ", array_keys($attributes));
	$sql .= ") VALUES ('";
	$sql .= join("', '", array_values($attributes));
	$sql .= "')";
	if($database->query($sql)){
		$this->id = $database->insert_id();
		return true;
	}else{
		return false;
	}
}

public function update(){
	global $database;
	$attributes = $this->sanitized_attributes();
	$attribute_pairs = array();
	foreach($attributes as $key => $value){
		$attribute_pairs[] = "{$key}='{$value}'";	
	}
	$sql = "UPDATE ".self::$table_name." SET ";
	$sql .= join(", ", $attribute_pairs);
	$sql .= " WHERE id=".$database->escape_value($this->id);
	$database->query($sql);
	return ($database->affected_rows() == 1) ? true : false;
}

public function delete(){
	global $database;
	$sql = "DELETE FROM ".self::$table_name." ";	
	$sql .= "WHERE id=".$database->escape_value($this->id);
	$sql .= " LIMIT 1";	
	$database->query($sql);
	return ($database->affected_rows() == 1) ? true : false;
}




} //end class pages
?>

 

 

 

this is the entire templates class

 

<?PHP
require_once(LIB_PATH.DS.'database.php');

class Templates extends Pages {

protected static $table_name="templates";

protected static $db_fields = array(
'id','name','type','activeTemp','defaultTemp','created','dateMod','timeMod');


public $id;
public $name;
public $type;
public $activeTemp;
public $defaultTemp;
public $created;
public $dateMod;
public $timeMod;



// "new" is a reserved word so we use "make"(or "build")
public static function make(

$id, $name="", $type="", $activeTemp="", $defaultTemp="", $created="", $dateMod="", $timeMod="") {

	if(!empty($name)) {

		$kw = new Templates();
		$kw->id = (int)$id;
		$kw->name = $name;
		$kw->type = $type;
		$kw->activeTemp = $activeTemp;
		$kw->defaultTemp = $defaultTemp;
		$kw->created = $created;
		$kw->dateMod = $dateMod;
		$kw->timeMod = $timeMod;

		return $kw;
	}else{
		return false;
	}
} //end function make



public static function find_layoutTemp(){
	global $database;

	$layoutTemps_id = Pages::$layoutTemps_id;

	$sql = "SELECT * FROM ".self::$table_name." WHERE id='".$database->escape_value($layoutTemps_id)."'";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}




// Common Database Methods
public static function find_all(){
	global $database;
	$sql = "SELECT * FROM ".self::$table_name."";
	return self::find_by_sql($sql);
}

public static function find_by_id($id=0){
	global $database;
	$sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($id)." LIMIT 1";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}

public static function find_by_sql($sql){
	global $database;
	$results_set = $database->query($sql);
	$object_array = array();
	while($row = $database->fetch_array($results_set)){
		$object_array[] = self::instantiate($row);
	}
	return $object_array;
}

public static function count_all(){
	global $database;
	$sql = "SELECT COUNT(*) FROM ".self::$table_name;
	$results_set = $database->query($sql);
	$row = $database->fetch_array($results_set);
	return array_shift($row);
}

public static function instantiate($result){
	$object = new self;
	foreach($result as $attribute => $value){
		if($object->has_attribute($attribute)){
			$object->$attribute = $value;
		}
	}
	return $object;
}

private function has_attribute($attribute){
	$object_vars = $this->attributes();
	return array_key_exists($attribute, $object_vars);
}


protected function attributes(){
	$attributes = array();
	foreach(self::$db_fields as $field){
		if(property_exists($this, $field)){
			$attributes[$field] = $this->$field;
		}
	}
	return $attributes;
}

protected function sanitized_attributes(){
	global $database;
	$clean_attributes = array();
	foreach($this->attributes() as $key => $value){
		$clean_attributes[$key] = $database->escape_value($value);
	}
	return $clean_attributes;
}

public function save(){
	return !empty($this->id) ? $this->update() : $this->create();
}

public function create(){
	global $database;
	$attributes = $this->sanitized_attributes();
	$sql = "INSERT INTO ".self::$table_name." (";
	$sql .= join(", ", array_keys($attributes));
	$sql .= ") VALUES ('";
	$sql .= join("', '", array_values($attributes));
	$sql .= "')";
	if($database->query($sql)){
		$this->id = $database->insert_id();
		return true;
	}else{
		return false;
	}
}

public function update(){
	global $database;
	$attributes = $this->sanitized_attributes();
	$attribute_pairs = array();
	foreach($attributes as $key => $value){
		$attribute_pairs[] = "{$key}='{$value}'";	
	}
	$sql = "UPDATE ".self::$table_name." SET ";
	$sql .= join(", ", $attribute_pairs);
	$sql .= " WHERE id=".$database->escape_value($this->id);
	$database->query($sql);
	return ($database->affected_rows() == 1) ? true : false;
}

public function delete(){
	global $database;
	$sql = "DELETE FROM ".self::$table_name." ";	
	$sql .= "WHERE id=".$database->escape_value($this->id);
	$sql .= " LIMIT 1";	
	$database->query($sql);
	return ($database->affected_rows() == 1) ? true : false;
}




} //end class templates
?>

 

 

this is the entire template index page

 

<?PHP
require_once("../includes/initialize.php");

//I WANT TO USE THIS  $temp = Templates::find_layoutTemp();

$temp = Templates::find_all();

foreach ($temp as $temps){
echo "layoutTemp id " .$temps->id . " <br />";
echo "layoutTemp name " .$temps->name ." <br />";
}



?>
<?PHP echo include_admin_templates_layouts($admin_template_layouts="header.php"); ?>
<div id="pageWrapper">
<div id="topContent">
<?PHP echo include_admin_templates_layouts($admin_template_layouts="topCont.php"); ?>
</div><!-- #topContent -->
<div id="content">
<?PHP 
echo include_admin_layout_temps($admin_layout_temp="contRight.php"); 
</div><!-- #content -->
  <div class="clear"></div>
</div><!-- #pageWrapper -->
<?PHP echo include_admin_templates_layouts($admin_template_layouts="footer.php"); ?>
</body>
</html>

<?PHP if(isset($database)) {$database->close_connection();}?>

 

you'll notice that at the moment if have hard coded in the layouts.

 

echo include_admin_layout_temps($admin_layout_temp="contRight.php"); 

 

but $admin_layout_temp="contRight.php" will change depending on what layoutTemp_id is passed to the template class.

 

OTHER CLASSES INCLUDE:

database

config

initialize

functions

sessions

 

but i dont you need those.

 

 

so anyway. all im tring to do is get the templateLayout_id from the current page then tell the template class to use the id to select the correct layout name from the database :)

HUGE THANKS.

rick

Link to comment
Share on other sites

Stop using 'global'.  It shouldn't be used AT ALL, regardless of whether you're writing OOP code or procedural code.

 

Objects can contain other objects.  If you have an object that requires another object in order to work, then create a private field for it and assign a concrete object to that field in your containing object's constructor.

Link to comment
Share on other sites

ok.

 

i got ride of the global here and it still works :) ill go through the rest :)

 

public function find_by_pageName($pName){
	$sql = "SELECT * FROM ".self::$table_name." WHERE pageName='".$pName."'";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}

Link to comment
Share on other sites

by removing the global from the function above i got rid of the $database->escape_value($pName) function from the database class.

 

this is the class

public function escape_value($value){
	if ($this->real_escape_string_exists) {
		if ($this->magic_qoutes_active) { $value = stripslashes($value); }
		$value = mysql_real_escape_string($value);
	} else {
		if (!$this->magic_qoutes_active) { $value = addslashes($value); }
	}
	return $value;
}

 

how would i put the function escape_value($value) back into my find_by_pageName($pName) function without using a global ?

 

public function find_by_pageName($pName){
	global $database;
	$sql = "SELECT * FROM ".self::$table_name." WHERE pageName='".$pName."'";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}

Link to comment
Share on other sites

would this work ?

 

.Database::escape_value($pName)

 

public static function find_by_pageName($pName){
	$sql = "SELECT * FROM ".self::$table_name." WHERE pageName='".Database::escape_value($pName)."'";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}

Link to comment
Share on other sites

First, I'm a bit weary about how you're using static classes.  They allow one to break scope, so they should be used sparingly.  Static classes are really best used as utility classes, not main components. 

 

Also, like I said before, objects can contain other objects.  Quick (canned) example:

 

class Example
{
   private $db;

   public function __construct($database)
   {
      $this->db = $database;
   }

   public function query($data)
   {
      $this->db->query($data);
   }
}

 

Your Pages should contain a reference to your database.  How that reference is obtained depends on whether or not you're accessing an actual instance of your class/object, or if you're merely accessing it in a static fashion.

Link to comment
Share on other sites

Hi all.

 

I came up with a solution.

 

Its not really what i was expecting and doesnt seem to be very oop .... but it works :)

 

If anyone can tell me a way of making this more oop ill be happy :)

 

so.... I simply used a session :)

 

1. get the page name and put it in a session

<?PHP
require_once("../includes/initialize.php");

$pName = "adminModules";
$_SESSION['pName'] = $pName;

 

2. get that pages details

 

Pages class

public static function find_by_pageName($pName){
    global $database;
	$sql = "SELECT * FROM ".self::$table_name." WHERE pageName='".$database->escape_value($pName)."'";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}

 

on the page

$page = Pages::find_by_pageName($pName);

 

3. then put the template name that that page used into another session

$_SESSION['page_temp'] = $page->layoutTemps;

 

4. then on the template index page get the template by including the session in the include

echo include_admin_layout_temps($admin_layout_temp = $_SESSION['page_temp'].".php"); ?>

 

 

now every time i call a different page name from the db it displays the correct template and layout

 

;D

 

 

ok.. so now for sorting out the globals ;)

Link to comment
Share on other sites

Hi all.

 

I came up with a solution.

 

Its not really what i was expecting and doesnt seem to be very oop .... but it works :)

 

If anyone can tell me a way of making this more oop ill be happy :)

 

so.... I simply used a session :)

 

1. get the page name and put it in a session

<?PHP
require_once("../includes/initialize.php");

$pName = "adminModules";
$_SESSION['pName'] = $pName;

 

2. get that pages details

 

Pages class

public static function find_by_pageName($pName){
    global $database;
	$sql = "SELECT * FROM ".self::$table_name." WHERE pageName='".$database->escape_value($pName)."'";
	$result_array = self::find_by_sql($sql);
	return !empty($result_array) ? array_shift($result_array) : false;
}

 

on the page

$page = Pages::find_by_pageName($pName);

 

3. then put the template name that that page used into another session

$_SESSION['page_temp'] = $page->layoutTemps;

 

4. then on the template index page get the template by including the session in the include

echo include_admin_layout_temps($admin_layout_temp = $_SESSION['page_temp'].".php"); ?>

 

 

now every time i call a different page name from the db it displays the correct template and layout

 

;D

 

 

ok.. so now for sorting out the globals ;)

 

 

DAMM - this worked yesterday. today it doesn't. when i go to the page it does start a new session :(

Link to comment
Share on other sites

Use a cookie if you want to store a specific value tied to a client over a period of time

 

I'm still not exactly sure what you're trying to accomplish. It's some sort of template system, where it first determines what kind of page is to be displayed, and then grabs a set template for that kind of page.

 

For example, you may have a 'article' page, a 'form' page, a 'comments' page, and a 'gallery' page.

You may then have a blue, green and yellow template, each with a specific set of HTML for the above pages.

 

You want to set what kind of page you want to display, and grab a template for that page, depending on what the user wants?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.