$sql=$pardConfig->prepare("SELECT * FROM ".$this->menu); i want to call to the db table dynamically.in here it was selecting only the menu.i want to call it from object ???
<?php
$dbhost=null;
$dbname=null;
$dbuser=null;
$dbpass=null;
$file = __DIR__ ."/config.json";
$array = file_get_contents($file);
$dbConfig=json_decode($array);
$pardConfig=new PDO('mysql:host='.$dbConfig[0].';'.'dbname='.$dbConfig[1],$dbConfig[2],$dbConfig[3]);
class pardDb
{
public $config = "pard_admin_config";
public $article = "pard_article";
public $menu = "pard_menu";
public $user = "pard_user";
public $images = "pard_images";
function pardTemplate($pardConfig,$pardDbTable){
$sql=$pardConfig->prepare("SELECT * FROM ".$this->menu);
$sql->execute();
$result=$sql->fetchALL(PDO::FETCH_OBJ);
$item = array_reverse($result);
return $item;
}
}
$pardDbTable = new pardDb();
$pardDbTable->pardTemplate($config,$pardConfig);
?>
I want one object and need to call it like this ?
echo $obj->menu;
echo $obj->article;
Try refactory this in one designe patterns (start your studing by Active Record and Data Mapper) add inheritance:
http://martinfowler.com/eaaCatalog/
after see the Magic Methods __get and __set
http://php.net/manual/en/language.oop5.overloading.php#object.get
Related
I am trying to make a base class ... tiny framework if you will just for practice
So I start with example of child class because it has less code !!
class User extends Base {
public $id ;
public $username ;
public $email ;
public $password ;
function __construct(){
$this->table_name = 'users';
$this->set_cols(get_class_vars('User'));
}
}
$u = new User;
$u->username = 'jason';
$u->email = 'j#gmail.com';
$u->insert();
Here is my Base class
class Base {
protected $table_name ;
protected $table_columns ;
protected function set_cols($cols){
unset($cols['table_name']);
unset($cols['table_columns']);
$this->table_columns = array_keys($cols);
}
public function insert(){
$colums = $values = array();
foreach($this->table_columns as $col )
{
if(!$this->$col) continue ;
$values[] = $this->$col ;
$colums[] = $col ;
}
$values = implode(',' , $values);
$colums = implode(',' , $colums);
echo $sql = "INSTER INTO ".$this->table_name ." ($colums)
VALUES ($values) ";
}
}
Here is the problem , I want to make filter or get method (basically reading from database) static and then return an array of objects from database data
class Base{
static function filter($conditions =array()){
$query_condition = $conditions ; // some function to convert array to sql string
$query_result = "SELECT * FROM ".$this->table_name ." WHERE $query_condition ";
$export = array();
$class = get_called_class();
foreach($query_result as $q )
{
$obj = new $class;
foreach($this->table_columns as $col )
$obj->$col = $q[$col];
$export[] = $obj;
}
return $export;
}
}
$users = User::filter(['username'=>'jason' , 'email'=>'j#gmail.com']);
Here is the problem , with filter as static function __construct in User class will not get called and table_columns, table_name will be empty
also in the filter method I can't access them anyway because they are not static ... I can make a dummy User object in the filter method and solve this problems but somehow it doesn't feel right
Basically I have a design problem any suggestion is welcomed
The problem is that the static object is not really "created" when you run statically.
If you want the constructor to run, but still in a static sort of way, you need a "singleton". This is where the object is created once and then you can re-use. You can mix this technique in a static and non-static way (as you're actually creating a "global" object that can be shared).
An example is
class Singleton {
private static $instance;
public static function getInstance() {
if (null === static::$instance) {
self::$instance = new static();
}
return self::$instance;
}
}
$obj = Singleton::getInstance();
Each time this gets the same instance and remembers state from before.
If you want to keep your code base with as few changes as possible, you can create yourself an "initialized" variable statically - you just need to remember to call it in each and every function. While it sounds great, it's even worse than a Singleton as it still remembers state AND you need to remember the init each time. You can, however, use this mixed with static and non-static calls.
class notASingletonHonest {
private static $initialized = false;
private static function initialize() {
if (!self::$initialized) {
self::$initialized = true;
// Run construction stuff...
}
}
public static function functionA() {
self::$initialize();
// Do stuff
}
public static function functionB() {
self::$initialize();
// Do other stuff
}
}
But read a bit before you settle on a structure. The first is far better than the second, but even then if you do use it, ensure that your singleton classes can genuinely be ran at any time without reliance on previous state.
Because both classes remember state, there are many code purists that warn you not to use singletons. You are essentially creating a global variable that can be manipulated without control from anywhere. (Disclaimer - I use singletons, I use a mixture of any techniques required for the job.)
Google "php Singleton" for a range of opinions and more examples or where/where not to use them.
I agree with a lot of your premises in your code and design. First - User should be a non static class. Second - Base base should have a static function that acts a factory for User objects.
Lets focus on this part of your code inside the filter method
1 $query_result = "SELECT * FROM ".$this->table_name ." WHERE $query_condition ";
2 $export = array();
3
4
5 $class = get_called_class();
6 foreach($query_result as $q )
7 {
8 $obj = new $class;
9
10 foreach($this->table_columns as $col )
11 $obj->$col = $q[$col];
12
13 $export[] = $obj;
14
15 }
The issue is that lines 1 and 10 are trying to use this and you want to know the best way to avoid it.
The first change I would make is to change protected $table_name; to const TABLE_NAME like in this comment in the php docs http://php.net/manual/en/language.oop5.constants.php#104260. If you need table_name to be a changeable variable, that is the sign of bad design. This will allow you change line 1 to:
$class = get_called_class()
$query_result = "SELECT * FROM ". $class::TABLE_NAME . "WHERE $query_condition";
To solve the problem in line 10 - I believe you have two good options.
Option 1 - Constructor:
You can rewrite your constructor to take a 2nd optional parameter that would be an array. Your constructor would then assign all the values of the array. You then rewrite your for loop (lines 6 to 15) to:
foreach($query_result as $q)
{
$export[] = new $class($q);
}
And change your constructor to:
function __construct($vals = array()){
$columns = get_class_vars('User');
$this->set_cols($columns);
foreach($columns as $col)
{
if (isset($vals[$col])) {
$this->$col = $vals[$col];
}
}
}
Option 2 - Magic __set
This would be similar to making each property public, but instead of direct access to the properties they would first run through a function you have control over.
This solution requires only adding a single function to your Base class and a small change to your current loop
public function __set($prop, $value)
{
if (property_exists($this, $prop)) {
$this->$prop = $value;
}
}
and then change line 10-11 above to:
foreach($q as $col => $val) {
$obj->$col = $val
}
Generally it is a good idea to seperate the logic of storing and retrieving the data and the structure of the data itself in two seperate classes. A 'Repository' and a 'Model'. This makes your code cleaner, and also fixes this issue.
Of course you can implement this structure in many ways, but something like this would be a great starting point:
class Repository{
private $modelClass;
public function __construct($modelClass)
{
$this->modelClass = $modelClass;
}
public function get($id)
{
// Retrieve entity by ID
$modelClass = $this->modelClass;
return new $$modelClass();
}
public function save(ModelInterface $model)
{
$data = $model->getData();
// Persist data to the database;
}
}
interface ModelInterface
{
public function getData();
}
class User implements ModelInterface;
{
public int $userId;
public string $userName;
public function getData()
{
return [
"userId" => $userId,
"userName" => $userName
];
}
}
$userRepository = new Repository('User');
$user = $userRepository->get(2);
echo $user->userName; // Prints out the username
Good luck!
I don't think there is anything inherently wrong with your approach. That said, this is the way I would do it:
final class User extends Base {
public $id ;
public $username ;
public $email ;
public $password ;
protected static $_table_name = 'users';
protected static $_table_columns;
public static function getTableColumns(){
if( !self::$_table_columns ){
//cache this on the first call
self::$_table_columns = self::_set_cols( get_class_vars('User') );
}
return self::$_table_columns;
}
public static function getTableName(){
return self::$_table_name;
}
protected static function _set_cols($cols){
unset($cols['_table_name']);
unset($cols['_table_columns']);
return array_keys($cols);
}
}
$u = new User;
$u->username = 'jason';
$u->email = 'j#gmail.com';
$u->insert();
And then the base class, we can use Late Static Binding here static instead of self.
abstract class Base {
abstract static function getTableName();
abstract static function getTableColumns();
public function insert(){
$colums = $values = array();
foreach( static::getTableColumns() as $col ){
if(!$this->$col) continue ;
$values[] = $this->$col ;
$colums[] = $col ;
}
$values = implode(',' , $values);
$colums = implode(',' , $colums);
echo $sql = "INSERT INTO ". static::getTableName() ." ($colums) VALUES ($values) ";
}
static function filter($conditions =array()){
$query_condition = $conditions ; // some function to convert array to sql string
$query_result = "SELECT * FROM ".static::getTableName() ." WHERE $query_condition ";
$export = array();
$columns = static::getTableColumns(); //no need to call this in the loop
$class = get_called_class();
foreach($query_result as $q ){
$obj = new $class;
foreach( $columns as $col ){
$obj->$col = $q[$col];
}
$export[] = $obj;
}
return $export;
}
}
Now on the surface this seems trivial but consider this:
class User extends Base {
public $id ;
public $username ;
public $email ;
public $password ;
final public static function getTableName(){
return 'users';
}
final public static function getTableColumns(){
return [
'id',
'username',
'email',
'password'
];
}
}
Here we have a completely different implementation of those methods from the first Users class. So what we have done is force implementation of these values in the child classes where it belongs.
Also, by using methods instead of properties we have a place to put custom logic for those values. This can be as simple as returning an array or getting the defined properties and filtering a few of them out. We can also access them outside of the class ( proper like ) if we need them for some other reason.
So overall you weren't that far off, you just needed to use static Late Static Binding, and methods instead of properties.
http://php.net/manual/en/language.oop5.late-static-bindings.php
-Notes-
you also spelled Insert wrong INSTER.
I also put _ in front of protected / private stuff, just something I like to do.
final is optional but you may want to use static instead of self if you intend to extend the child class further.
the filter method, needs some work yet as you have some array to string conversion there and what not.
I have a PHP class called Product:
class Product {
$id;
$name;
}
And another class that get data from database:
$stm = $this->dsn->prepare($sql);
$stm->execute();
$rst = $stm->fetchAll(PDO::FETCH_ASSOC);
How can I convert this PDO resultset ($rst) to an array of objects Product?
Use the PDO::FETCH_CLASS argument.
class Product {
public $id;
public $name;
}
$stm = $this->dsn->prepare($sql);
$stm->execute();
$result = $stm->fetchAll( PDO::FETCH_CLASS, "Product" );
http://php.net/manual/en/pdostatement.fetchall.php
Just change the way you're calling fetchAll()
$rst = $stm->fetchAll(PDO::FETCH_CLASS, 'Product');
My approach in this case would be to use a helper function within the Product class that builds a new instance of the object and returns it provided the inputs from the PDO.
Such as
public static function buildFromPDO($data) {
$product = new Product();
$product->id = $data["id"];
$product->name = $data["name"];
return $product;
}
Then inside of your PDO call, loop through the return and array_push onto an array containing all your products built via this function.
$products = array();
foreach ($rst as $r) {
array_push($products, Product::buildFromPDO($r));
}
You also might want to consider using an ORM if it seems like you'll be doing a ton of this kind of stuff.
You have to write a method to do it.
class Product {
$id;
$name;
public function loadData($data){
$this->id = $data['id'];
$this->name = $data['name'];
}
}
$Product = new Product();
$Product->loadData($database_results);
Or, if you're going to be doing this for every object, use a constructor..
class Product {
$id;
$name;
public function __construct($id, $pdo){
$pdo->prepare("select * from table where id = :id");
// do your query, then...
$this->id = $data['id'];
$this->name = $data['name'];
}
}
$Product = new Product($id, $pdo);
You can use constructor arguments (http://php.net/manual/en/pdostatement.fetchall.php)
$result = $stm->fetchAll( PDO::FETCH_CLASS, "Product", array('id','name'));
Note: properties must be public
I want to use a associative array (outcome of a PDO query) in a class, so that I can construct a DIV with some database content.
How to get the array inside the Class? In the while loop I want to make an object, in the Class of this object I want to construct the HTML.
while($data = $stmt->fetch( PDO::FETCH_ASSOC )){
$html = new class;
echo $html;
}
If you want your while loop to be able to work about like you've written it, you can write the constructor of the class so that it accepts the data as an argument, then implement the div output in the __toString method.
class HtmlDivFormatter {
private $data;
public function __construct($data) {
$this->data = $data;
}
public function __toString() {
return '<div>' . $this->data['column_name'] . '</div>';
// whatever HTML you have in mind
}
}
while ($data = $stmt->fetch( PDO::FETCH_ASSOC )) {
$html = new HtmlDivFormatter($data);
echo $html;
}
see PDO::FETCH_CLASS or PDO::FETCH_INTO
more info here http://php.net/manual/en/pdostatement.fetch.php and this
PHP PDO fetching into objects
and some example code:
<?php
$sql = 'SELECT firstName, lastName FROM users';
$stmtA = $pdo->query($sql);
$stmtA->setFetchMode(PDO::FETCH_CLASS, 'Person');
$objA = $stmtA->fetch();
var_dump($objA);
//first create the object we will fetch into
$objC = new Person;
$objC->firstName = "firstName";
$objC->lastName = "lastName";
$stmtC = $pdo->query($sql);
$stmtC->setFetchMode(PDO::FETCH_INTO, $objC);
$objC = $stmtC->fetch(); // here objC will be updated
var_dump($objC);
class Person{
public $firstName;
public $lastName;
}
I am having trouble on accessing to an instance of a singleton class in PHP MVC. Basically the MVC looks like
First of all I have included and instantiated objects in the init.php as
// include objects
include('app/Database.php');
include('app/models/m_template.php');
include('app/models/m_categories.php');
// create objects
$tdatabase = new Database();
$Template = new Template();
$Categories = new Categories();
and in m_categories.php I tried to use the $tdatabase object as:
<?php
class Categories {
private $db_table = 'category';
function __construct() { }
public function get_categories() {
$data = array();
$res = $tdatabase->query("SELECT * FROM " . $this->db_table . " ORDER BY name");
foreach ($res as $dataRow):
$data[] = array('id' => $dataRow['id'],
'name' => $dataRow['name'],
'img' => $dataRow['img'],
'alt' => $dataRow['alt'],
);
endforeach;
return $data;
}
}
and finally in index.php I have:
<?php
include('app/init.php');
echo '<pre>';
print_r($Categories->get_categories());
echo '</pre>';
but I am getting following errors:
can you please let me know why this is happening and how I can fix this?
Update 1:
Update 2
Categories object doesn't have any information about outside variables. You sholud pass Database object to your Categories object e.g. by constructor or by method parameter.
init.php
$tdatabase = new Database();
$Template = new Template();
$Categories = new Categories($tdatabase);
m_categories.php
class Categories {
protected $database;
private $db_table = 'category';
function __construct($database) {
$this->database = $database;
}
public function get_categories() {
$data = array();
$res = $this->database->query("SELECT * FROM " . $this->db_table . " ORDER BY name");
// (...)
}
your variable tdatabase is out of scope. you either need to pass it into the function, or set it as a class member variable in the constructor or via a setter
i.e.
public function get_categories(Database $tdatabase) {
$data = array();
$res = $tdatabase->query("SELECT * FROM " . $this->db_table . " ORDER BY name");
I often see code like this though, and I (almost) always recommend, especially for new projects that you use the model/mapper pattern because it is more easily extensible and is more maintainable. See here for an example:
OOP PHP PDO My First Project , Am I doing right?
I am aware that a class cannot be defined within a class in php, however I'm curious if there's another way to achieve the desired effect.
I currently have a set of 3 objects used to conduct a search. The first is called $search_request. It contains properties like $keywords (string), $search_results_per_page (int), $page_requested (int), $owner_id (int)
I also have an object called $search_result, it contains properties like $total_matches (int), $result_set (array of objects)
Finally I have the $search_handler object which contains the $search_request and $search_result, along with functions that build the $search_result based on the $search_request.
Usage goes like so:
$search_handler = new search_handler();
$search_handler->search_request->keywords = "cats, dogs";
$search_handler->search_request->search_results_per_page = 10;
$search_handler->search_request->page_search_requested = 1;
$search_handler->get_search_result();
echo $search_handler->search_result->total_matches;
foreach($search_handler->search_result->result_set)
{
//do something
}
All of this works fine. The problem is I want to repeat this model for different objects, so currently I'm forced to use the hackey solution of the "search_" prefix on each class.
I'd like to have something like:
class search
{
public class request
{
$keywords = "";
$search_results_per_page = 5;
$page_requested = 1;
}
public class result
{
$total_matches = null;
$result_set = array();
}
public get_results()
{
//check cache first
$cached = look_in_cache(md5(serialize($this->request)));
if($cached)
{
$this->result->result_set = $cached;
$count = count($cached);
$this->result->total_matches = $count;
}
else
{
//look in db
$results = get_results_from_database($this->request->keywords); //db call goes here
$this->result->result_set = $results;
$count = count($results);
$this->result->total_matches = $count;
}
}
}
//usage
$search = new search();
$search->request->keywords = "cats, dogs";
$search->request->search_results_per_page = 10;
$search->request->page_search_requested = 1;
$search->get_results();
echo $search->results->total_matches;
foreach($search->results->result_set as $result)
{
//do something
}
If for whatever reason you don't want to have those classes you need in different files you can do the following
<?php
class search
{
var $request;
var $result;
public function __construct()
{
$this->request = new StdClass();
$this->request->keywords = "";
$this->request->search_results_per_page = 5;
$this->request->page_requested = 1;
$this->result = new StdClass();
$this->result->total_matches = null;
$this->result->result_set = array();
}
// ...
}
$search = new search();
var_dump($search->request, $search->result);
?>
There's several things to suggest here
First, if you're using PHP 5.3 or later, consider using namespaces and autoloading. That would allow you to make classes like \Cat\Search and \Dog\Search.
Second, I would avoid setting object properties directly. I would highly suggest you make your variables protected and use getters and setters instead. Limit your object interaction to methods and you can control the process much more easily.
$search_handler = new search_handler();
$search_handler->setKeywords(array("cats", "dogs"));
You could define your request and result classes as separately, and then have variables in your main class be assigned to instances of those.
Something like:
class result{
...
}
class request{
...
}
class search{
var results;
var request;
function __construct(){
$results = new ArrayObject();
$request = new stdClass();
}
...
}
Then you can assign/append to the list of results in your search function
and you can just assign a request object to your 'request' variable
$this->results[] = $newresult;
and loop through them when displaying