PHP OOP Class Help - php

I'm am unsure on how to move part of my code into a class.
<?php
class InfoTest {
private $info_results;
public function __construct() {
$dbc = get_dbc();
$info = $dbc->query ("SELECT info_id, info_title FROM text");
if ($dbc->error) {
printf("Error: %s\n", $dbc->error);
}
while ($info_row = $info->fetch_array())
{
$info_results[]= $info_row;
}
$info->free();
$this->info_results = $info_results;
}
public function setInfo() {
$this->info_results = $info_results;
}
public function getInfo() {
return $this->info_results;
}
public function __destruct() {
}
}
?>
<?php
$display = new InfoTest();
foreach ($display->getInfo() as $info_row) {
?>
<!-- html -->
<?php echo $info_row['info_title']."</a><br />"; ?>
<!-- html -->
Sub-Info:
<?php
$dbc = get_dbc();
$si_title = $dbc->query ("SELECT info_title FROM text WHERE info_id = ".$info_row['info_id']."");
if ($dbc->error) {
printf("Error: %s\n", $dbc->error);
}
$num =$si_title->num_rows;
$count = 0;
while ($sub_info = $si_title->fetch_array())
{
$sub_info_title = $sub_info['info_title'];
if ($count!=$num-1)
{
echo $sub_info_title." , ";
$count++;
}
else echo $sub_info_title;
}
?>
<!-- html -->
<?php } ?>
I'm unsure how to move the Sub-Info(code after Sub-Info:) into a class. Does it go in the same class as InfoTest, a class of its own, or doesn't go into a class at all?
Sub-Info Code:
<?php
$dbc = get_dbc();
$si_title = $dbc->query ("SELECT info_title FROM text WHERE info_id = ".$info_row['info_id']."");
if ($dbc->error) {
printf("Error: %s\n", $dbc->error);
}
$num =$si_title->num_rows;
$count = 0;
while ($sub_info = $si_title->fetch_array())
{
$sub_info_title = $sub_info['info_title'];
if ($count!=$num-1)
{
echo $sub_info_title." , ";
$count++;
}
else echo $sub_info_title;
}
?>

In your class you have already all information. So an alternative to a sql-query could be an additional method, which searches all titles with a special id in the private field info_results. E.g.:
public function getInfoTitles($info_id) {
$titles = array();
foreach ($this->info_results as $info_row) {
if ($info_row['info_id'] == $info_id)
$titles[] = $info_row['info_title'];
}
}
return $titles;
}
Your Sub-Info Code is then:
echo implode(', ', $display->getInfoTitles($info_row['info_id']));

The general idea of OOP is to couple data with methods that process that data. So, if you feel that some piece of your data are processed in the same way multiple times, it's a good idea to introduce a class that will incapsulate that data and logic.
Of course it emerges a lot of other questions: how many classes should one have, how should they interact with each other, which part of business logic should go in which class etc. There is no universal, always-true answer to that questions, but some general approaches to address that questions were developed: the design patterns. There are some books on the topic, one of the most known is Gang-of-Four (GoF) Design Patterns.
That's general thoughts on the topic. In your particular case, I would suggest you creating new class ItemInfo, so InfoTest class is responsible only for quering the DB and creating Instances of this new class.
class InfoTest {
private $items;
public function __construct() {
$this->items = new Array();
}
private function queryItems($itemId){
$dbc = get_dbc();
$info = $dbc->query("SELECT info_id, info_title FROM text");
if ($dbc->error) {
printf("Error: %s\n", $dbc->error);
}
while ($info_row = $info->fetch_array())
{
$item = new ItemInfo($info_row);
$this->items[] = $item;
}
$info->free();
}
public function getItems($itemId){
if (empty($this->items)){
$this->queryItems($itemId);
}
return $this->items;
}
/* Other functions. */
public function __destruct() {
}
}
Class ItemInfo{
private $id, $title;
function __construct(Array $params){
$this->id = $params['item_id'];
$this->title = $params['item_title'];
}
function getTitle(){
return $this->title;
}
function toString(){
retirn "I'm item {$this->id}, my title is {$this->title}";
}
}
And your code will be as simple as
$item_test = new ItemTest();
$items = $item_test->getItems($item_id);
$titles = array();
foreach ($items as $item){
//you may process your items in any way you need
$titles[] = $item->getTitle();
}
echo implode(',', $titles);

Related

Query result to a collection of object

I have a database phpmyadmin, I created a class :
<?php
class Ticket
{
private $NumDossier = 0;
private $NomTicket ="";
private $Service = "" ;
private $Impact = 0;
private $Urgence = "";
private $DateOuverture = "";
public function __construct($p_NumDossier, $p_NomTicket,$p_Service,$p_Impact,$p_Urgence,$p_DateOuverture)
{
$this->NumDossier = $p_NumDossier;
$this->NomTicket = $p_NomTicket;
$this->Service = $p_Service;
$this->Impact = $p_Impact;
$this->Urgence = $p_Urgence;
$this->DateOuverture = $p_DateOuverture;
}
public function getNumDossier()
{
return $this->NumDossier;
}
public function getNomTicket()
{
return $this->NomTicket;
}
public function getService()
{
return $this->Service;
}
public function getImpact()
{
return $this->Impact;
}public function getUrgence()
{
return $this->Urgence;
}
public function getDateOuverture()
{
return $this->DateOuverture;
}
}
?>
For all row that my query return I want to create an object and add it to a collection.
My code :
$connexion = cnx();
if($connexion) {
$requete="SELECT * FROM ticket '";
$result = mysqli_query($connexion, $requete);
$result = mysqli_query($connexion, $requete);
$row = mysqli_fetch_assoc($result);
}
$test = new Ticket(0,"","",0,"","");
while($row) {
//create object for each line and add it to an collection
}
If you have a solution/lead me to this issue.
Thanks for read !
I have to assume that the beginning part of your code is correct, so I copied that. But I changed it further on. You want to retrieve multiple rows, so I put the mysqli_fetch_assoc inside the while loop. With each new row I create a new ticket and put it in a 'collection' array.
$connection = cnx();
if ($connexion) {
$query ="SELECT * FROM ticket";
$result = mysqli_query($connection, $query);
if ($result === false) die("The query [$query] could not be executed.");
$collection = [];
while($row = mysqli_fetch_assoc($result)) {
$collection[] = new Ticket($row["NumDossier"],
$row["NomTicket"],
$row["Service"],
$row["Impact"],
$row["Urgence"],
$row["DateOuverture"]);
}
echo "<pre>";
print_r($collection);
echo "</pre>";
}
So I used a simple array for the collection. I used the default numeric array indexing because I wouldn't know what to replace it with. $row["NomTicket"] seems a logical choice.

Assign the value to the Object in php

Actually after fetching the data from the Database, i want to create a new Object and insert this object to the array but when i check the array it shows the NULL value
here is my code:
<?php
$query = "sql query";
$filter_Result = mysqli_query($con, $query);
$newOrders = Array();
while ($row = mysqli_fetch_array($filter_Result)) {
$order;
$orderId = $row['order_id']; //fetch row id
$temp = check_id($newOrders, $orderId);
if ($temp != null) {
$order = $temp;
} else {
echo " <br>";
$order = new Order($row['order_id'], $row['status'], $row['created_Date']);
$newOrders[] = $order;
}
$item = new Item($row['status'], $row['quantity']);
$order->AddItem($item, null);
}
function check_id($newOrders, $orderId) {
$length = count($newOrders);
for ($i = 0; $i < $length; $i++) {
if ($newOrders[$i]->$orderId == $orderId)
return $newOrders[$i];
}
return null;
}
foreach ($newOrders as $order) {
}
?>
You have a variable in your Order class
var $order_Id;
But then you try to assign value to $orderId which does not exist
$this->orderId = $orderId;
I would suggest turning all PHP errors on while developing. You can include this in your php code to see if you get any errors. It is very hard to see all the small errors with naked eye :) Let PHP do it for you.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
More about error reporting here.
You have several small mistakes, e.g. using "this" incorrectly, using different name for "orderId", plus a wrong name for the constructors. The constructor name should be "Order" or "__construct", same for "Item" constructor.
class Order {
/* Member variables */
var $orderId;
var $status;
var $createdDate;
var $items = array();
function Order($orderId, $status, $createdDate)
{
$this->orderId = $orderId;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
$c = new Order(1, 'OK', 'today');
print_r($c);
Now i found the Solution in the PHP we have to use __construct() for the creating a Constructor....
So use it __construct instead of class name for more info visit:
__construct() vs SameAsClassName() for constructor in PHP
new_order.php
<?php
class Order {
/* Member variables */
var $order_Id;
var $status;
var $createdDate;
var $items = array();
function __Order($order_Id, $status, $createdDate)
{
$this->order_Id = $order_Id;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
class Item {
var $productId;
var $productName;
var $quantity;
var $personalization;
function __Item($productId, $quantity)
{
$this->productId = $productId;
$this->productName = $productName;
$this->quantity = $quantity;
$this->personalization = $personalization;
}
}
?>

PDO request within a class

Here is my class :
class ProfileLink {
function profileLink(PDO $pdo, $string, $i=0)
{
if ($i!=0) {
$link = $string . '-' . $i;
} else {
$link = $string;
}
$req = $pdo->prepare('SELECT link FROM users WHERE link = ?');
$req->execute(array($link));
$nb = $req->rowCount();
$req->closeCursor();
if ($nb > 0) {
$i++;
return profileLink($pdo, $string, $i);
} else {
return $link;
}
}
}
When I call the profileLink function from the class, it doesn't work, but if I call it outside the class, everything is ok. It might be a problem with the PDO, what do you think ?
require_once ('lib/profileLink.class.php');
$profileLink = new ProfileLink();
$link = $profileLink->profileLink($pdo, $string);
I would store the instance of PDO as a class property so that it can be easily accessed within the class. Note that my example uses slightly different syntax (modern PHP).
class ProfileLink {
protected $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function profileLink($string, $i=0)
{
if ($i!=0) {
$link = $string . '-' . $i;
} else {
$link = $string;
}
$req = $this->pdo->prepare('SELECT link FROM users WHERE link = ?');
$req->execute(array($link));
$nb = $req->rowCount();
$req->closeCursor();
if ($nb > 0) {
$i++;
return profileLink($string, $i);
} else {
return $link;
}
}
}
$profileLink = new ProfileLink($pdo);
2 Things:
here
return profileLink($pdo, $string, $i);
you are missing a $this, because it's no regular function but a class method:
return $this->profileLink($pdo, $string, $i);
And second, your method has the same name as the class (except of the first capital letter), and thus seems to be interpreted as constructor. I have just tested this:
class Test {
function test() {
echo "test";
}
}
$t = new Test();
And it outputs "test".
So you should rename your method to getLink or something similar.

Template engine {var} doesnt work

I have made a template system but the {var} doesnt output the worth.
It just output {var}.
Here is my template class:
<?php
class Template {
public $assignedValues = array();
public $tpl;
function __construct($_path = '')
{
if(!empty($_path))
{
if(file_exists($_path))
{
$this->tpl = file_get_contents($_path);
}
else
{
echo 'Error: No template found. (code 25)';
}
}
}
function assign($_searchString, $_replaceString)
{
if(!empty($_searchString))
{
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
}
}
function show()
{
if(count($this->assignedValues) > 0)
{
foreach ($this->assignedValues as $key => $value)
{
$this->tpl = str_replace('{'.$key.'}', $value, $this->tpl);
}
}
echo $this->tpl;
}
}
?>
And here is what I execute on the index:
<?php
require_once('inc/classes/class.template.php');
define('PATH', 'tpl');
//new object
$template = new Template(PATH.'/test.tpl.html');
//assign values
$template->assign('title', 'Yupa');
$template->assign('about', 'Hello!');
//show the page
$template->show();
?>
I really need some help, if you can help I'd would be very grateful.
Instead of line:
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
You should have:
$this->assignedValues[$_searchString] = $_replaceString;
and it will work.
Of course I assume that inside your template file you have content:
{title} {about}
You should change
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
to this:
$this->assignedValues["{".$_searchString . "}"] = $_replaceString ;
this will only replace your keywords with values.

array to public variable in php

I have a array i want its value to be "public $somevariable". Here is my function how it looks like.
public function __construct(){
global $database;
$result = $database->query("SHOW COLUMNS FROM ".self::$tabel_name."");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
$attributes_var = array();
while ($row = $database->fetch_array($result)) {
$attributes_var[] = $row[0];
}
}
foreach($attributes_var as $key)
{
public $$key;
}
}
But its showing syntax error on "public $$key". I want to use the dynamic generated variable as public variable and want to use them outside the class.
Any suggestion?
Thank you!
You can do like below, the default value is null.
foreach($attributes_var as $key)
{
$this->{$key} = null;
}

Categories