How to access private variables in another page by function? - php

randomClass.php
class randomClass
{
private $perPage = 8;
private $startPage = 0;
function perPage($perPage)
{
$this->db->perPage = $perPage;
}
function startPage($startPage)
{
$this->db->startPage = $startPage;
}
public function usingBothVariables()
{
$sth = $this->db->prepare("SELECT rndm FROM table LIMIT ?, ?");
$sth->execute(array($this->startPage, $this->PerPage));
$row = $sth->fetchAll();
return $row;
}
{
index.php
if($randomVariable < 1)
use startPage function here = 0;
else
use startPage function here = $randomVariable * use $perPage function here;

In randomClass:
public function getPerPage(){
return $this->perPage;
}
public function getStartPage(){
return $this->startPage;
}
Now in your index.php you can call those methods to get yuor variables.

Related

Creating a Cursor Based Pagination System in PHP

I am trying to figure out how how to create my own simple cursor based pagination system in PHP and am having difficulty trying to understand how star starting_after and starting_before works as mentioned in this medium.com post for how the company stripe deals with cursor pagination. In my case I am using the id column that is in ascending order to hopefully make this work. The issue that I am having is getting an id for the first "page". Currently my first page would direct to the second page since starting_after leads to the next page and not the currently page. Any advice for how to build this out would be awesome. I already created page based pagination, but think that cursor pagination would be more useful for most of my cases.
I have attached the two files that I have created thus far to try to get this to work.
Pagination class
<?php
require_once "DB.php";
class New_Pagination {
private $table = "";
private $limit;
private $starting_after = "";
private $starting_before = "";
private $db;
public function __construct() {
$this->db = DB::getInstance();
}
public function getLimit(): int {
return $this->limit;
}
public function setLimit(int $limit): void {
$this->limit = $limit;
}
public function getStartingAfter(): string {
return $this->starting_after;
}
public function setStartingAfter(string $starting_after): void {
$this->starting_after = $starting_after;
}
public function getStartingBefore(): string {
return $this->starting_before;
}
public function setStartingBefore(string $starting_before): void {
$this->starting_before = $starting_before;
}
public function getTable(): string {
return $this->table;
}
public function setTable(string $table): void {
$this->table = $table;
}
public function idExists($id) {
$result = $this->db->find(self::getTable(), [
"select" => "id",
"conditions" => "id = $id",
"fetchType" => "single"
]);
if (empty($result)) {
return FALSE;
} else {
return $result->id;
}
}
public function getData($starting_after, $starting_before) {
self::setStartingAfter($starting_after);
self::setStartingBefore($starting_before);
$starting_after = self::getStartingAfter();
$starting_before = self::getStartingBefore();
$data = [];
$order = !empty($starting_after) ? "ASC" : "DESC";
if (empty($starting_after) && empty($starting_before)) {
$data["data"] = $this->db->find(self::getTable(), [
"select" => "*",
"order" => "id ASC",
"limit" => self::getLimit(),
"fetchType" => "all"
]);
} else {
$data["data"] = $this->db->find("carousel_image", [
"select" => "*",
"conditions" => "id >= '$starting_after' OR id <= '$starting_before'",
"order" => "id $order",
"limit" => self::getLimit(),
"fetchType" => "all"
]);
}
$next = self::idExists($data["data"][count($data["data"]) - 1]->id + 1);
$previous = self::idExists($data["data"][0]->id - 1);
$data["cursor"] = [
"next" => $next,
"previous" => $previous
];
return $data;
}
public function generateLink() {
$test = self::getData("", "");
$test2 = [];
$test2[0] = $test;
$i = 0;
do {
$test2[$i] = $test;
$test = self::getData($test["cursor"]["next"], "");
$i++;
$test2[$i] = $test;
} while ($test["cursor"]["next"] !== FALSE);
$test2[$i] = $test;
echo "<ul>";
$j = 1;
foreach ($test2 as $key => $val) {
if ($val["cursor"]["next"] !== FALSE) {
$url = "/process.php?starting_after=" . $val["cursor"]["next"];
echo "<li>";
echo "<a href='$url'>$j</a>";
echo "</li>";
$j++;
}
}
echo "<ul>";
}
}
Test file
$pagination = new New_Pagination();
$pagination->setLimit(2);
$pagination->setTable("carousel_image");
echo "<pre>";
$pagination->generateLink();
echo "</pre>";
The cursors are useful to prevent scan big tables and allow to move in very big sources (files, external resources, etc., etc.). In the majority of the cases, cursors are provided by binary libraries and supported by the core of the related system (mysql, files). If you try to emulate this behavior in not natural way you must take care because you could add overhead and get unexpected results.
In the other hand, is very useful to have a pagination class, but be aware, this class have some problems.
getData is very expensive because it performs 3 queries to get a batch of results
the class is too verbose, the getters and setters add too much noise
the results are sorted using very rare criteria. Remember, if you are in search results you need the same order moving to the next page and moving to the previous page
My suggestions...
Create interfaces
<?php
interface CursorAble {
public function fetchNext ($startingAfter);
public function fetchPrev ($startingBefore);
public function getPreviousLink ();
public function getNextLink ();
}
interface Pageable {
public function getCollectionSize ();
public function getPageSize ();
public function getPagesCount ();
public function getPageLinks ();
}
When you create interfaces you ensures that the classes expose the desired behavior and furthermore delegate the specialized details to the concrete implementations. The concrete implementations can define it dependencies in the constructor, something very good when you relies on dependency injection.
CursorAble implementation example
<?php
class PdoCursorAbleTable implements CursorAble {
private $pdo;
private $table;
private $results;
private $pageSize;
public function __construct (PDO $pdo, $table, $pageSize = 100) {
$this->pdo = $pdo;
$this->table = $table;
$this->pageSize = (int)$pageSize ?: 100;
}
public function fetchNext ($startingAfter) {
$s = $this->pdo->prepare("select * from {$this->table} where id > :starting_after limit {$this->pageSize}");
$s->bindValue(':starting_after', $startingAfter, PDO::PARAM_INT);
$s->execute();
$this->results = $s->fetchAll() ?: [];
return $this->results;
}
public function fetchPrev ($startingBefore) {
$s = $this->pdo->prepare("select * from {$this->table} where id < :starting_before limit {$this->pageSize}");
$s->bindValue(':starting_before', $startingBefore, PDO::PARAM_INT);
$s->execute();
$this->results = $s->fetchAll() ?: [];
return $this->results;
}
public function getPreviousLink () {
return !$this->results ? '' : '?starting_before=' . $this->results[0]->id;
}
public function getNextLink () {
if (!$this->results || count($this->results) < $this->pageSize) return '';
return '?starting_after=' . $this->results[count($this->results)]->id;
}
}
And the Pageable example
<?php
class PdoPageableTable implements Pageable {
private $pdo;
private $table;
private $pageSize;
private $collectionSize;
public function __construct (PDO $pdo, $table, $pageSize = 100) {
$this->pdo = $pdo;
$this->table = $table;
$this->pageSize = $pageSize;
}
public function getCollectionSize () {
if ($this->collectionSize === null) {
$s = $this->pdo->prepare("select count(id) from {$this->table}");
$s->execute();
$this->collectionSize = $s->fetchColumn('0');
}
return $this->collectionSize;
}
public function getPageSize () {
return $this->pageSize;
}
public function getPagesCount () {
return ceil($this->collectionSize / $this->getPageSize());
}
public function getPageLinks () {
$pages = [];
foreach (range(1, $this->getPagesCount()) as $page) {
$pages[] = '?page=' . $page;
}
return $pages;
}
}
The test file
<?php
$pagination = new PdoCursorAbleTable($pdo, 'carousel_image', 2);
echo "<pre>";
$startingAfter = 0;
$results = $pagination->fetchNext($startingAfter);
foreach ($results as $result) {
// do something
}
echo $pagination->getNextLink();
echo "</pre>";

PHP object is not being created

I have received the following error:"Fatal error: Call to a member function session_type() on a non-object".
Supposedly I'm not creating an object in the variable "$tabsessiontype2". I don't see the reason why the object isn't created. Thanks for you help.
Here is my TeacherController.php
if(isset($_POST['search']) && $_POST['sessiontype_name']){
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}
elseif($tabsessiontype2->session_type()=='XO'){
$view='teacherxo.php';
}
elseif($tabsessiontype2->session_type()=='note'){
$view='teachernote.php';
}
}
This is the function I call:
public function select_session_type2($name_session_type) {
$query = "SELECT * FROM session_types WHERE session_types.name_session_type='$name_session_type'";
$result = $this->_db->query($query);
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
}
Here is the SessionType class:
class SessionType{
private $_code_session_type;
private $_name_session_type;
private $_quarter_session_type;
private $_code_lesson;
private $_session_type;
public function __construct($code_session_type,$name_session_type, $quarter_session_type, $code_lesson,$session_type){
$this->_code_session_type = $code_session_type;
$this->_name_session_type = $name_session_type;
$this->_quarter_session_type = $quarter_session_type;
$this->_code_lesson = $code_lesson;
$this->_session_type = $session_type;
}
public function code_session_type(){
return $this->_code_session_type;
}
public function name_session_type(){
return $this->_name_session_type;
}
public function quarter_session_type(){
return $this->_lastname;
}
public function code_lesson(){
return $this->_email_student;
}
public function session_type(){
return $this->_session_type;
}
}
It looks like the function select_session_type2 is returning an array:
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
and you are expecting an object:
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}

passing an instance of a class to another class in order to use its variables

I'm trying to pass an instance of my Generator class to another class to use some of the variables. The Generator class instance works fine but when i passed it to another (SelectStrategy) class it seems it is not passing the variable at all. I'm not sure what I'm doing wrong - I used var_dump on the called function to check what it gives me but it's just blank.
Function
class Generator
{
//properties for self
private $s_charge;
public $connection;
public $task_priority;
public $fog_mode = true;
public $nodes = array();
public $type;
public function generateNodesSpecs() {
$node = array();
for ($i = 0; $i < 100; $i++) {
$charge1 = mt_rand(30,100);
$node['charge'] = $charge1;
//array_push($node, $charge1);
$hops = mt_rand(0,4);
$node['hops'] = $hops;
//array_push($node, $hops);
$resource1 = mt_rand(0,100);
if ($resource1 <= 50) {
if ($resource1 <=10){
$node['connection'] = '4G';
//array_push($node, '4G');
}
else {
$node['connection'] = '3G';
//array_push($node, '3G');
}
}
else if ($resource1 > 50 && $resource1 <= 60) {
$node['connection'] = 'WiFi';
//array_push($node, 'WiFi');
}
else {
}
$resource2 = mt_rand(0,100);
if ($resource2 <=60) {
$node['additional'] = 'CPU';
//array_push($node, 'CPU');
}
else {
$node['additional'] = 'none';
}
$this->nodes[] = $node;
//array_push($nodes, $node);
unset($node);
}
//compare which get the resources
//var_dump($this->nodes[0]);
}
class SelectStrategy {
//take in generator class instance
private $generator;
private $priority;
private $size;
private $slaves = array();
private $found_slave = null; //will hold item with max val;
public function __construct($generator) {
$this->generator = $generator;
}
private function selectSlaves() {
$max = -9999999; //will hold max val
foreach($this->generator->nodes as $k=>$v)
{
if($v['charge']>$max)
{
$max = $v['charge'];
$this->found_slave = $v;
}
}
var_dump($this->found_slave);
}
}
And classes/function calls
$generator = new Generator();
$generator->generateNodesSpecs();
$select_strategy = new SelectStrategy($generator);
$select_strategy->selectSlaves();
The $this->generator->nodes is a 2D array
global $generator;
in every function of SelectSlave should do it

php Fatal error: Class '' not found in..doesnt specify the class

I'm getting a class not found error but without the name of the class. I got the code from here
but when I try to run it, it gives the following error..
Fatal error: Class '' not found in C:\Program Files\Apache Software Foundation\Apache24\Apache24\htdocs\framework\library\controller.class.php on line 16
and the following is the controller
<?php
class Controller {
protected $_model;
protected $_controller;
protected $_action;
protected $_template;
function __construct($model, $controller, $action) {
$this->_controller = $controller;
$this->_action = $action;
$this->_model = $model;
include 'model.class.php';//other similar posts suggested this but its not working
$this->$model = new $model;
$this->_template = new Template($controller,$action);
}
function set($name,$value) {
$this->_template->set($name,$value);
}
function __destruct() {
$this->_template->render();
}
}
I'm assuming its the model class which is not being found. The model class code is
<?php
class Model extends SQLQuery {
protected $_model;
function __construct() {
$this->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$this->_model = get_class($this);
$this->_table = strtolower($this->_model)."s";
}
function __destruct() {
}
}
and sqlquery class is
<?php
class SQLQuery {
protected $_dbHandle;
protected $_result;
/** Connects to database **/
function connect($address, $account, $pwd, $name) {
$this->_dbHandle = #mysql_connect($address, $account, $pwd);
if ($this->_dbHandle != 0) {
if (mysql_select_db($name, $this->_dbHandle)) {
return 1;
}
else {
return 0;
}
}
else {
return 0;
}
}
/** Disconnects from database **/
function disconnect() {
if (#mysql_close($this->_dbHandle) != 0) {
return 1;
} else {
return 0;
}
}
function selectAll() {
$query = 'select * from `'.$this->_table.'`';
return $this->query($query);
}
function select($id) {
$query = 'select * from `'.$this->_table.'` where `id` = \''.mysql_real_escape_string($id).'\'';
return $this->query($query, 1);
}
/** Custom SQL Query **/
function query($query, $singleResult = 0) {
$this->_result = mysql_query($query, $this->_dbHandle);
if (preg_match("/select/i",$query)) {
$result = array();
$table = array();
$field = array();
$tempResults = array();
$numOfFields = mysql_num_fields($this->_result);
for ($i = 0; $i < $numOfFields; ++$i) {
array_push($table,mysql_field_table($this->_result, $i));
array_push($field,mysql_field_name($this->_result, $i));
}
while ($row = mysql_fetch_row($this->_result)) {
for ($i = 0;$i < $numOfFields; ++$i) {
$table[$i] = trim(ucfirst($table[$i]),"s");
$tempResults[$table[$i]][$field[$i]] = $row[$i];
}
if ($singleResult == 1) {
mysql_free_result($this->_result);
return $tempResults;
}
array_push($result,$tempResults);
}
mysql_free_result($this->_result);
return($result);
}
}
/** Get number of rows **/
function getNumRows() {
return mysql_num_rows($this->_result);
}
/** Free resources allocated by a query **/
function freeResult() {
mysql_free_result($this->_result);
}
/** Get error string **/
function getError() {
return mysql_error($this->_dbHandle);
}
}
I'm new to PHP and I'm using PHP 5.5.15. I know I should probably switch this to pdo, but i just want to get this working before gettin jiggy with it.
Any help much appreciated
Simple said, you have this function for your controller:
function __construct($model, $controller, $action) {
$this->$model = new $model;
}
You need to give a $model, wich would be the name of a class. You give no name. This is why class "" can not be found.
If we would write this:
$controller = new Controller("mycrazymodel", null, null);
It means:
function __construct($model, $controller, $action) {
//$this->$model = new $model;
$this->$model = new mycrazymodel; //above means this, if $model = "mycrazymodel"
}
So what does this mean for you?
Locate the call of the Controller::__construct method, which typical mean new Controller(...) and make sure, you give the classname as $model parameter.
Take a look at the manual for further information: http://php.net/manual/en/language.namespaces.dynamic.php

can't echo php class variable

I want to write a php simple pagination class. Here is my code:
<?php
class Pagination {
public $rowsPerPage;
public $currentPage;
public $totalPages;
public $totalRows;
public $firstElement;
public $lastElement;
public function paginate()
{
if(isset($_GET['page'])){
$this->currentPage = $_GET['page'];
}
$this->totalPages = $this->totalRows/$this->rowsPerPage ;
return $this->totalPages;
$this->firstElement = $this->currentPage-1)*$this->rowsPerPage+1;
return $this->firstElement;
}
}
$totalRecords = 55;
$paginator = new Pagination();
$paginator->totalRows = $totalRecords;
$paginator->rowsPerPage = 5;
$paginator->paginate();
echo $paginator->totalPages;
echo $paginator->firstElement;
?>
I can echo $paginator->totalPages; but not $paginator->firstElement.
What I do wrong ?
Thanks
Your paginate function has two return statements.
When the code hits the return $this->totalPages;, it will stop running the function. Therefore, the $this->firstElement = ... line is never ran.

Categories