How to get variable from one class to another in Joomla? - php

How do I get the getState variable from one class to another?
Exactly I need to get value of "filter.search". How can I do that?
jimport('joomla.filesystem.folder');
abstract class SroHelper
{
public static function checkIP()
{
SroModelItems::getState(filter.search); ---- ??
}
}
jimport('joomla.application.component.model');
class SroModelItems extends JModel
{
protected function populateState($ordering = null, $direction = null)
{
$this->setState("filter.search", $jform["search$dbextra"]);
}
}

You have two modules to store information in the session automatically from a get / post request and then to read it back:
JFactory::getApplication()->getUserStateFromRequest($key, $request)
JFactory::getApplication()->setUserState($key, $value);
Just ensure you are saving the information before you try to retrieve it!

Related

Codeigniter Query result returning Custom result object with setters

How exactly does CI custome object works ?
As per CI documentation You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $row)
{
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
}
This is a very nice feature yet what Ci does is it will return an array of User objects and set attributes from row to it.
i have a problem with it that i want to have more control on what attributes to be publicly accessed and what to be modified before setting/getting.
how can i accomplish this ? can i tell CI to pass all attributes to constructor so that class can populate its own data ?
example class User
class User{
private $data=array();
protected $CI;
//public $id,$name,$dob,$gender,$role,$username,$password,$salt,$picture,$lastactive;
function __construct($data=null)
{
$this->data = $data; // i want to save data to a private var and allow attr. throu getters only
}
function set_password($p){
$this->generateSalt();
$this->data->password = $p.$this->data->salt;
}
}
In a nutshell::
I want to use custom_result_object but i dont want codeigniter to populate class attributes for me, instead i want the class to receive those attrs and populate it him self the way he this its appropriate.
I found your question while looking for a solution for myself.
After digging a bit in the documentation I managed to figure it out:
class user_item {
// you can declare all the attributes you want as private
private $id,$name,$dob,$gender,$role,$username,$password,$salt,$picture,$lastactive;
function __construct(){
// you can use the constructor to format data as needed
$this->username = strtouppper($this->username);
}
public function set_password($p){
$this->generateSalt();
$this->password = $p.$this->salt;
}
public function get_password(){
return $this->password;
}
}
Once set up, you can instantiate this class from $this->db->result()
class User_model extends CI_Model {
public function get_user($id){
return $this->db->get_where('users', array('id' => $id), 1)->result('user_item');
}
}
And call any public method or attribute of the class as needed
class Users extends CI_Controller {
function __construct(){
$this->load->model('user');
}
public function profile($user_id){
var $myUser = $this->user->get_user($user_id);
$myUser->set_password('myPassword');
echo $myUser->get_password();
}
}
I have simplified the code to make it clearer, but you get the idea.
this example controller using result array and object
if ($this->session->userdata('id_jurusan') ==1) {
$where=array('id_jurusan'=>$this->session->userdata('id_jurusan'));
$value = $this->session->userdata('id_jurusan');
$value2 = $this->session->userdata('username');
$data['rule']=$this->guru_mod->get_where($where,'forward_changing')->result();
$data['fuzzy']=$this->guru_mod->get_data_all('fuzzy')->result();
$data['artikel']=$this->guru_mod->get_data_all('artikel')->result();
$data['kondisi']=$this->guru_mod->get_where($where,'kondisi')->result();
$data['artikel2'] = $this->guru_mod->get_data_all2('artikel','id_jurusan',$value);
$data['riwayat_rule'] = $this->guru_mod->get_data_all2('forward_changing','username',$value2);
$data['kondisi_rule'] = $this->guru_mod->get_data_all2('kondisi','id_jurusan',$value);
$this->load->view('guru/daftar_rule',$data);
}

PHP select from DB and mantain the values without selecting again

I have a specific table in the DB that contains some static data.
This data is anyway required by many methods and each method calls the DB again and again to grab this data.
Now is there a way in PHP to select the data from the DB and mantain it as it was a constant or a SESSION ( I cannot use sessions in this case ) ?
What I am trying to do is to put the request in the contruct and to make the variable static, but it does not change the result. Each time a method calls the static variable, the select in the DB is done anyway..
class service {
public static $actions;
public function __construct() {
self::$actions = self::getActions();
}
public static function getActions() {
$actions = self::$db->select('_actions', '*');
return $actions;
}
}
Your code is already pretty close. You just need to add a check to see if the data has already been queried, and make sure you're using the static class variable, not a local variable.
You should realize that static variables and constructors live in two different worlds. Static variables are persistent for the lifetime of the class - constructors run once per instance.
public static $actions = null;
public static function getActions() {
if (self::$actions === null) {
self::$actions = self::$db->select('_actions', '*');
}
return self::$actions;
}
Look into caching the data - http://www.phpfastcache.com/
You can use a library like the link above or write something simple that serializes the data and writes it to a file. If the file exists then use that data and deserialize it on subsequent requests for the same data set.
Similar to Sam Dufel's answer, but do the check and query in the constructor.
class service {
public static $actions;
public function __construct() {
if (!self::$actions) {
self::$actions = self::$db->select('_actions', '*');
}
}
public static function getActions() {
return self::$actions;
}
}

Random object per page request with SilverStripe

Lets say you show a random statement per page request and use a function to return a random object like:
Statement::get()->sort("RAND()")->limit("1");
But now in the template you want to reference it twice in different places but it should be the same statement and not a randomly different one. How would you make sure to get the same random object per page request?
What about defining a function with a static variable that remembers the object?
public function rndObj() {
static $obj = null;
if(!isset($obj)){
$obj = Statement::get()->sort("RAND()")->limit("1")->first();
}
return $obj;
}
and then use rndObj in the template.
One way to do this is to fetch the random statement in the controller init function and assign this to a private variable. We add a getRandomStatement function to fetch the random statement:
class Page_Controller extends ContentController {
private $randomStatement;
public function init() {
parent::init();
$this->randomStatement = Statement::get()->sort('RAND()')->limit(1)->first();
}
public function getRandomStatement() {
return $this->randomStatement;
}
}

Codeignieter data is not initialized in index function

I am trying to initialize data in index function of controller, so that initialized data can be used in subsequent functions of controller. But the problem is data is not being displayed when I am trying to access it from other function. All of this is just to follow a sort of object oriented pattern.
Here is my code.
class Dashboard extends CI_Controller
{
private $account_data; /*Declaration*/
private $profile_data;
function __construct() {
// code...
}
function index() /*Here I am initializing data*/
{
$this->load->model('db_model');
$this->account_data = $this->db_model->get_row();
$this->profile_data = $this->db_model->get_row();
$this->load->view('user/dashboard');
}
function function account_details()
{
print_r($this->account_data); // This displays nothing
}
/*other function...*/
}
Idea is to get data once and use it for other functions and if data is updated again calls a function to initialize it.
But it is not working out. Please help me. Also suggest if I am following right approach.
Thanks for your time.
index method is not initializer, its default page/sub_method,
if you call the "*account_details*" in url as index.php/dashboard/account_details the index wont be called.
try put the code on constructor,
class Dashboard extends CI_Controller
{
private $account_data; /*Declaration*/
private $profile_data;
function __construct() { /*Here I am initializing data*/
parent::CI_Controller(); // Thank you Sven
$this->load->model('db_model');
$this->account_data = $this->db_model->get_row();
$this->profile_data = $this->db_model->get_row();
}
function index()
{
$this->load->view('user/dashboard');
}
function function account_details()
{
print_r($this->account_data); // This displays nothing
}
/*other function...*/
}
Note : don't the models or other computations on __construct() if you don't need on all methods of this controller.
create a private method like "model_initializer()" put this codes on this scope, and the call it in your other methos as $this->model_initialize(); if you need.
Thanks yo Sesama Sesame for note,

How do I use a variable within an extended class public variable

Have a class that I am using, I am overriding variables in the class to change them to what values I need, but I also not sure if or how to handle an issue. I need to add a key that is generated to each of this URLs before the class calls them. I cannot modify the class file itself.
use Theme/Ride
class ETicket extends Ride {
public $key='US20120303'; // Not in original class
public $accessURL1 = 'http://domain.com/keycheck.php?key='.$key;
public $accessURL2 = 'http://domain.com/keycheck.php?key='.$key;
}
I understand that you cannot use a variable in the setting of the public class variables. Just not sure what would be the way to actually do something like this in the proper format.
My OOP skills are weak. I admit it. So if someone has a suggestion on where I could read up on it and get a clue, it would be appreciated as well. I guess I need OOP for Dummies. =/
---- UPDATE ---
The initial RIDE class has 2 URLs set.
public $accessURL1 = "http://domain.com/index.php";
public $accessURL2 = "http://domain.com/index2.php";
I was to override them so the RIDE class will use my new domains.
I can add the following and it works...
class ETicket extends RIDE {
public $accessURL1 = 'http://mydomain.com/myindex.php';
public $accessURL2 = 'http://mydomain.com/myindex2.php';
}
However, I also want to pass a variable from elsewhere ($key) as a parameter to the URL when I override them so when i call RIDE it has a URL with the value of KEY at the end. (?key=keyvalue)
Your close, if you do not want to allow calling code to change the $key, you can do something like:
class ETicket extends Ride {
public function getKey()
{
return 'US20120303';
}
public function generateUrl()
{
return 'http://domain.com/keycheck.php?key=' . $this->getKey();
}
}
// Calling code example
$eTicket= new ETicket();
// $key is a member of ETicket class, so just call on generateUrl which will
// build and return the url
var_dump($eTicket->generateUrl());
You can also permit calling code to change the key if needed, by adding a public setter/getter:
class ETicket extends Ride {
protected $key;
public function setKey($key)
{
$this->key = $key;
}
public function getKey()
{
return $this->key;
}
public function generateUrl()
{
return 'http://domain.com/keycheck.php?key=' . $this->getKey();
}
}
// Calling code example
$eTicket= new ETicket();
$eTicket->setKey('US20120303');
var_dump($eTicket->generateUrl());
-- UPDATE --
There are a couple of options, you can either append the key to your url as part of the calling code, like this:
$eTicket= new ETicket();
$url = $ride->accessURL1 . '?key=US20120303';
Or, use a method (changed slightly to accept key directly) as I described earlier:
class ETicket extends Ride
{
public function generateUrl($key)
{
return $this->accessURL1 . '?key=' . $key;
}
}
$eTicket= new ETicket();
$url = $eTicket->generateUrl('US20120303');
I guess the point is, you cannot do what you originally asked without which is to concatenate a variable to a member variable initialization.

Categories