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;
}
}
Related
I have this controller
class PageController extends Controller
{
private $myid;
public funciton index(){
}
public function viewbyid($id){
$this->myid = $id;
return view('someview');
}
public function getRecord(){
$id = $this->myid;
echo $id; //it would be null here,if I am going to access this method.
return view('anotherview');
}
}
Yes, you can access private varible, in side class any where, Your using OOPS PHP. So may be problem is you might be accessing getRecord() method with diff object.
For Eg:
$obj=new PageController();
$obj->viewbyid("Test");
$obj->getRecord();//Then it will display the result
If your reinitialize an object or creating new object then that object will reallocate memory, so previous saved values will not be present.
For Eg:
$obj=new PageController();
$obj->viewbyid("Test");
$obj=new PageController();//$obj will allocate memory in diff location so your previous values will be initialized to default.
$obj->getRecord();//Then it will display result as null
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!
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;
}
}
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.
I'm working on a test in phpunit and I'm running into an issue. I have a public function on my class that I am trying to test. Depending on the parameters passed in to the method, a protected function also in my test class will be called one or two times. I currently have a test in place to check that the return data is correct, but I would also like to make sure the protected method is being called the correct number of times.
I know that a mock object will allow me to count the number of times a function is called, but it will also override the value returned by the protected function. I tried using a mock object with no "will" section, but it would just return null, not the actual value for the protected method.
ExampleClass
public function do_stuff($runTwice){
$results = do_cool_stuff();
if($runTwice){
$results = 2 * do_cool_stuff();
}
return $results;
}
protected function do_cool_stuff()
{
return 2;
}
In my test, I want to check whether do_cool_stuff() was called once or twice, but I still want the return values of both functions to be the same so I can test those as well in my unit test.
tl;dr
I want to count the number of times a protected method in my test object is called (like you can do with a mock object) but I still want all the methods in my test method to return their normal values (not like a mock object).
Alternatively, revert back to rolling your own testable stand-in. The following aint pretty, but you get the idea:
class ExampleClass {
public function do_stuff($runTwice) {
$results = $this->do_cool_stuff();
if ($runTwice) {
$results = 2 * $this->do_cool_stuff();
}
return $results;
}
protected function do_cool_stuff() {
return 2;
}
}
class TestableExampleClass extends ExampleClass {
/** Stores how many times the do_cool_stuff method is called */
protected $callCount;
function __construct() {
$this->callCount = 0;
}
function getCallCount() {
return $this->callCount;
}
/** Increment the call counter, and then use the base class's functionality */
protected function do_cool_stuff() {
$this->callCount++;
return parent::do_cool_stuff();
}
}
class ExampleClassTest extends PHPUnit_Framework_TestCase {
public function test_do_stuff() {
$example = new ExampleClass();
$this->assertEquals(2, $example->do_stuff(false));
$this->assertEquals(4, $example->do_stuff(true));
}
public function test_do_cool_stuff_is_called_correctly() {
// Try it out the first way
$firstExample = new TestableExampleClass();
$this->assertEquals(0, $firstExample->getCallCount());
$firstExample->do_stuff(false);
$this->assertEquals(1, $firstExample->getCallCount());
// Now test the other code path
$secondExample = new TestableExampleClass();
$this->assertEquals(0, $secondExample->getCallCount());
$secondExample->do_stuff(true);
$this->assertEquals(2, $secondExample->getCallCount());
}
}
I wonder though whether counting the number of times a protected method has been called is really a good test. It's coupling your test to the implementation pretty hard. Does it really matter whether it is called twice, or are you more interested in the interactions with other objects? Or maybe this is pointing towards do_cool_stuff needing a refactor into two separate methods:
class ExampleClass {
public function do_stuff($runTwice) {
if ($runTwice) {
return $this->do_cool_stuff_twice();
} else {
return $this->do_cool_stuff_once();
}
}
//...
}
Try setting a global variable prior to utilizing the class.
$IAmDeclaredOutsideOfTheFunction;
then use it to store the count and simply check it after your functions and classes have been called.