php putting an array from _construct into function - php

II'm using an API and was wondering why I am having trouble getting an array to cross into a function. The following works fine but how can I make it work for an array.
public function __construct()
{
parent::__construct(); // Init parent constructor
$this->dbConnect();
$this->test();
}
public function test()
{
$this->category = "bracelets";
}
private function piece()
{
// Pass an array into this function here and then use depending on array key
$cat = $this->category;
}
So instead of a constant $this->category="bracelets. I would like this to be an array. e.g.
public function test()
{
$array = [
"foo" => "bar",
"bar" => "foo",
];
$this->category = $array;
}
Ok, this has been resolved. It was due to a minor error elsewhere. For a moment I believed there was an issue with arrays in a restful API.
I hope this is useful to any others who wish to pass one function results to another in an api class.

Looking at you code, it seems you want the category property to be an array of all categories, read from the database..?
I did spot some bugs in your code:
You have variable name mixups on $cat_array vs. $cat_arr
You select cat column from DB but try read category
I have made slight changes in your test() method to fix it:
public function __construct()
{
parent::__construct(); // Init parent constructor
$this->dbConnect();
$this->test();
}
// Array with name of all categories, indexed by category id
private $category;
public function test()
{
$query = "SELECT c.id, c.cat FROM category c order by c.id asc";
$cat = $this->mysqli->query($query)
or die ($this->mysqli->error . __LINE__);
if ($cat->num_rows > 0) {
$cat_array = array();
while ($crow = $cat->fetch_assoc()) {
$id = $crow['id'];
$cat_array[$id] = $crow['cat'];
//$cat_array[$crow['id']]=$crow['category'];
}
$this->category = $cat_array;
//$this->response($this->json($result), 200); // send details
}
}
private function piece()
{
// Pass an array into this function here and then use depending on array key
$cat = $this->category;
// Check if it is working as expected
print_r($cat);
}

Related

Automatically sort all Arrays in controller when getting from database PHP

So I have this controller that passes an associative array called $pagedata to the view. Inside this array are 3 more associative arrays, and the view renders 3 select elements with the array data as options. I want to sort the 3 arrays but I don't want to write sort 3 times here or add order_by into the query methods, because there are dozens of similar pages and I don't want to write hundreds of sort method calls. I was told I could solve this in the constructor. I was wondering if there's an OOP solution that lets me automatically sort all child arrays inside $pagedata.
class Sku extends CI_Controller {
protected $pagedata = array();
public function __construct()
{
parent::__construct();
$this->load->model('mc');
}
public function inventory()
{
$this->pagedata['class_ids'] = $this->mc->get_class_ids();
$this->pagedata['retail_readys'] = $this->mc->get_all_retail_ready();
$this->pagedata['statuses'] = $this->mc->get_all_status();
}
}
Edit:
I'm exploring using an ArrayObject or wrapping $pagedata in an object and watch for changes.
ok this will be painfull for codeigniter but yes a kind of solution
public function __construct()
{
parent::__construct();
$this->load->model('mc');
$class_ids = $this->mc->get_class_ids();
$class_ids = $this->sortAscending($class_ids, $key);
$this->pagedata['class_ids'] = $class_ids;
$retail_readys = $this->mc->get_all_retail_ready();
$class_ids = $this->sortAscending($class_ids, $key);
$this->pagedata['class_ids'] = $class_ids;
$statuses = $this->mc->get_all_status();
$statuses = $this->sortAscending($class_ids, $key);
$this->pagedata['statuses'] = $statuses;
}
function sortAscending($accounts, $key)
{
$ascending = function($accountA, $accountB) use ($key) {
if ($accountA[$key] == $accountB[$key]) {
return 0;
}
return ($accountA[$key] < $accountB[$key]) ? -1 : 1;
};
usort($accounts, $ascending);
return $accounts;
}
public function inventory()
{
// already get values
//$this->pagedata['class_ids'] = $this->mc->get_class_ids();
//$this->pagedata['retail_readys'] = $this->mc->get_all_retail_ready();
//$this->pagedata['statuses'] = $this->mc->get_all_status();
$this->load->view('index',$this->pagedata);
}
public function another_function()
{
// already get values
//$this->pagedata['class_ids'] = $this->mc->get_class_ids();
//$this->pagedata['retail_readys'] = $this->mc->get_all_retail_ready();
//$this->pagedata['statuses'] = $this->mc->get_all_status();
$this->load->view('another page',$this->pagedata);
}

PDO FETCH_CLASS multiple rows into array of objects

I'm trying to fetch multiple rows of bookings from a database and I want each one to be an instance of a specific class - so I attempted to store them within a multidimensional array.
So far it works in terms of creating the array of objects, however I need the index for the array to be the booking ID so that I can easily access each one. For example:
$bookings[id] => booking Object ( [name:protected] => name, [time:protected] => time )
Is this possible and is it the best way to go about what I want to achieve? Any help would be hugely appreciated, here's the code:
class create_bookings {
private $db;
protected $error;
function __construct($db, $current, $end) {
$this->db = $db;
$query = "SELECT id, name, time
FROM bookings";
$stmt = $this->db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_CLASS, 'booking');
print_r($result);
}
}
...and the 'booking' class is just a set of properties:
class booking {
private $db;
protected $name;
protected $time;
}
Instead of building a class to create the booking objects, it would be advisable to either create a standalone function, or a function within a parent class to achieve this. The issue I run in to with using fetchAll() with the FETCH_CLASS parameter, is that the objects do not automatically have access to the database object, causing you to need to iterate over the objects afterwards anyways, so I simply build the __construct() method to capture the $db and generated array.
Assuming you go the route of a standalone function:
function create_bookings($db, $current, $end) {
$query = "SELECT id, name, time
FROM bookings";
$stmt = $db->prepare($query);
$stmt->execute();
$result = array()
$bookings = $stmt->fetchAll();
if($bookings) {
foreach($bookings as $booking) {
$result[$booking['id']] = new booking($db, $booking);
}
}
return $result;
}
class booking {
private $db;
public $id;
public $name;
public $time;
public function __construct($db, $array) {
if(/*validate your array here*/) {
$this->db = $db;
$this->id = $array['id'];
$this->name = $array['name'];
$this->time = $array['time'];
}
}
}
Yes there is a way to do this.
The trick is PDO::FETCH_GROUP. Just do
$result = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_CLASS, 'booking');
The only downside to this is that there will be an array in every result before the Object
There's a simple way to remove the array too
$output= array_map('reset',$result);

PHP call public variable in another class

I am trying to call a public variable used in a class in another class. I am able to call the variable but it returns a blank array.
Code that I am working on,
Class One:
class fruits {
public $ID = array();
private function getFruitID() {
$fruitID = array('1' , '2', '3' , '4' , '5' );
return $fruitID;
}
private function getFruitsName() {
$fruitName = array('apple' , 'orange' , 'kiwi' , 'grapes' , 'mango');
return $fruitName ;
}
public function getstock() {
$this->ID = getFruitID();
/* Prints the ID list here */
$this->name = getFruitsName();
/* This function renders to the template */
}
}
Class Two:
class TestPage{
public function displayFruits() {
require_once ('fruits.php');
$fruits = new fruits();
$data = $fruits->ID;
echo($data);
/* displays an empty array */
}
}
When I echo $data inside displayFruits() on TestPage, it prints a blank array and not the actual ids. I am stuck with getting the ids on TestPage class. I could use a return, but that way I would end with just one variable, and I have multiple variables inside that function. Any help would be much appreciated.
you are not contructing the array with anything ..
public $ID = array();
is blank... until you call getFruitID
you can add it into the constructor if you need.
constructors PHP
function __construct( ){
$this->getstock();
}
This means when you create your object new Fruit();
It will assign the array in its creation.
At the moment it is empty.
public $ID = array();
Add below to populate array
class TestPage{
public function displayFruits() {
require_once ('fruits.php');
$fruits = new fruits();
$fruits->getstock();
$data = $fruits->ID;
echo($data);
}
}

How to call and view an array in a function

I'm new to PHP and Kohana.
I would like to know how to call an array in a function.
I'm having the variable $productlist and I would like to add more elements into it with a function.
public $productlist = array();
public function action_index()
{
$product = new Product("Laptop","HP4897");
$product2 = new Product("TV","Samsung 8773");
$productlist[] = product;
$productlist[] = product2;
$this->add_product_to_array("Ebook","Everything you want to know");
$this->show_productlist();
}
public function add_product_to_array($product_name, $product_description)
{
$newproduct = new Product($product_name, $product_description);
array_push($productlist,$newproduct);
}
public function show_productlist(){
foreach($productlist as $key => $value)
{
print_r($value->get_product_name().'</br>');
}
}
and this is the exception i'm getting:
*ErrorException [ Warning ]: array_push() expects parameter 1 to be array, null given*
if I'm adding foreach($this->productlist as $key => $value), it tells me it can't find productlist.
Product.php
class Product {
private $_product_name;
private $_product_description;
function __construct($name,$description)
{
$this->_product_name = $name;
$this->_product_description = $description;
}
public function get_product_name()
{
return $this->_product_name;
}
//etc
PHP Classes and Objects - The Basics
Inside the class when you access the $productlist array you need to use $this->productlist. You seem to have known this in the Product class. What happened?

Codeigniter active record not reseting after call, multiple models

When I call a model from another model (using CodeIgniter &get_instance), there is an unwanted behavior, the constraints passed to the $this->db->where() and $this->db->select() previous model moves to the next model.
I'm working on scenario we need to call a model into another (chained / dependency) - though does not seem a common practice among the community CodeIgniter.
Below I have detailed my senary.
/Application/models/data_access/produto/produto_dao.php:
class Produto_dao extends CI_Model
{
private $ci;
public function __construct()
{
parent::__construct();
$this->ci =& get_instance();
$this->dependenciesEntity();
}
private function dependenciesEntity()
{
$this->ci->load->model('entity/produto/produto');
$this->ci->load->model('entity/produto/produto_collection');
$this->ci->load->model('data_access/produto/categoria_dao');
}
public function getProdutos($filtros, $inicioPaginacao = 0)
{
$this->db->select('produtos.id');
$this->db->select('produtos.uri');
$this->db->select('produtos.seo_keywords AS keywords');
$this->db->where('produtos.id', '1349');
$result = $this->db->get('produtos');
var_dump( $this->db->last_query() );
return $this->collectResult($result->result());
}
private function collectResult($result)
{
$produtoCollection = new Produto_collection();
foreach($result as $value){
$produto = new Produto();
$produto->setId($value->id);
$produto->setCategoria( $this->getCategoria( $value->id ) );
$produto->setUri($value->uri);
$produto->setKeywords($value->keywords);
$produtoCollection->addProduto($produto);
}
return $produtoCollection;
}
private function getCategoria($idProduto)
{
$categoria = new Categoria_dao();
return $categoria->getCategoria($idProduto);
}
}
And here we have the dependence,
/application/models/data_access/produto/categoria_dao.php
class Categoria_dao extends CI_Model
{
private $ci;
public function __construct()
{
parent::__construct();
$this->ci =& get_instance();
$this->dependenciesEntity();
}
private function dependenciesEntity()
{
$this->ci->load->model('entity/produto/categoria');
$this->ci->load->model('entity/produto/categoria_collection');
}
public function getCategoria($id)
{
$this->db->select('categorias.id');
$this->db->select('categorias.id_pai AS idPai');
$this->db->where('categorias.id',$id);
$result = $this->db->get('categorias');
var_dump( $this->db->last_query() );
return $this->collectResult($result->result());
}
private function collectResult($result)
{
$categorias = new Categoria_collection();
foreach($result as $value){
$categoria = new Categoria();
$categoria->setId($value->id);
$categoria->setCategoriaPai( $this->getCategoriaPai( $value->idPai ) );
$categorias->addCategoria($categoria);
}
return $categorias;
}
private function getCategoriaPai($id)
{
if($id){
return $this->getCategoria($id);
}
return new Categoria_collection();
}
}
When I run, I got the following results of $this->db->last_query()
Produto_dao.php last_query()
SELECT produtos.id, produtos.uri, produtos.seo_keywords AS keywords FROM produtos WHERE produtos.id = '3454'
Categoria_dao.php last_query()
SELECT produtos.id, produtos.uri, produtos.seo_keywords AS keywords, categorias.id, categorias.id_pai AS idPai FROM categorias WHERE categorias.id = '39' AND produtos.id = '3454'
Any idea why this happens?
You have to flush the cache to do this consecutive query as it is explain here :
CodeIgniter : Active recode caching
First query
$this->db->start_cache();
$this->db->select('field1');
$this->db->stop_cache();
When you are going to execute a new query, do :
$this->db->flush_cache();
It's going to give you a brand new query to work with.
Hope it helps.

Categories