The title may not make sense, not sure how to word it. Anyways, i'm practicing curl and OOP at the same time here with the riot games API. the API is kind of set up dumb where some info you want to request requires input that you wouldn't know off hand, so it requires another separate call to get the required info first.
class league
{
const URL = 'http://prod.api.pvp.net/api/lol/na/v1.1/';
const URL_2 = 'http://prod.api.pvp.net/api/lol/na/v2.1/';
const KEY = 'key';
public function summonerByName($summoner_name)
{
$request = 'summoner/by-name/' . $summoner_name . '?api_key =' . self::KEY;
return $this->fetch($request);
}
public function recentGamesByName($summoner_name)
{
//need to make two calls for this since you cant get recent games by name in the api
$id = summonerByName($summoner_name);
//now get recent games
$request = 'game/by-summoner/' . $id->id . '/recent';
return $this->fetch($request);
}
private function fetch($request)
{
$url = self::URL . $request . '?api_key=' . self::KEY;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
return json_decode($data);
}
}
this is returning Fatal error: Call to undefined function summonerbyname()
if i use all this extra code below in the public function recentGamesByName() instead of $id = summonerByName() it works fine, but it seems unnecessary, and i want to replace that with just the function.
$grg = self::URL . 'summoner/by-name/' . $summoner_name . '?api_key=' . self::KEY;
$placeholder = curl_init($grg);
curl_setopt($placeholder, CURLOPT_RETURNTRANSFER, 1);
$ph_result = curl_exec($placeholder);
curl_close($placeholder);
$ph_result = json_decode($ph_result);
$id = $this->summonerByName($summoner_name);
You may want to read up on OOP.
A couple of things to remember about OOP. When you're INSIDE the class and need to call another function, you use the the special $this variable.
So you would use:
$someVariable = $this->summonerByName($summoner_name);
to get the results from that function.
If you're OUTSIDE the class and need to access that function, then you need to assign the entire class to a variable like so:
$league = new league();
and then you can access any function within the class using that variable.
So you could do...
$someVariable = $league->summonerByName($summoner_name);
if you had already assigned the class to a variable name $league. By the way, that $league variable? It's called an object. Thus Object Oriented Programming. Objects are kinda like arrays, but use a different syntax. You can print_r an object just like you can print_r an array. When accessing an object's variable you use the $objectName->variableName syntax instead of $arrayName['variablename'] syntax that you use in arrays.
Related
I have tried the solutions indicated here on stackoverflow, the code below uses one of them, recommended and voted as the right way to do it, but it doesn't work for me, why?
In fact the href results empty.
<?php
//URLS LIST
$nameA = 'http://www.example.com';
$nameB = 'http://www.example.com';
$nameC = 'http://www.example.com';
class bannClass {
private $class_varA;
private $class_varB;
private $class_varC;
public $username = '';
public function __construct($nameA, $nameB, $nameC) {
$this->class_varA = $nameA;
$this->class_varB = $nameB;
$this->class_varC = $nameC;
}
public function check_userOne() {
$url = 'https://example.com/wp-content/uploads/sponsor/' . $this->username . '/sponsor1.jpg';
return '<img src="' . $url . '" alt="Sponsor"/>';
}
public function check_userTwo() {
$url = 'https://example.com/wp-content/uploads/sponsor/' . $this->username . '/sponsor2.jpg';
return '<img src="' . $url . '" alt="Sponsor"/>';
}
public function check_userThree() {
$url = 'https://example.com/wp-content/uploads/sponsor/' . $this->username . '/sponsor3.jpg';
return '<img src="' . $url . '" alt="Sponsor"/>';
}
}
Also how can i make those 3 variables at the top dynamic in php? instead of "name" something like $($this->username . 'A') , $($this->username . 'B') , etc.
EDIT: the above class is being instantiated in another php file like so:
<?php
require_once('myclass.php');
$bannClass = new bannClass();
$bannClass->username = $data['username'];
//etc.
and used like:
<?php echo $bannClass->check_userOne();?>
As it is written, you must inject 3 values when it is instantiated. If you have error reporting turned on in your development environment (and you really should), it would have complained when you instantiated it as $bannClass = new bannClass();
This is how this object should be instantiated:
$nameA = 'http://www.example.com';
$nameB = 'http://www.example.com';
$nameC = 'http://www.example.com';
$bannClass = new bannClass($nameA, $nameB, $nameC);
I would make a few suggestions:
Don’t mix logic and presentation. A good rule of thumb to follow is no html outside of the view. Objects are generally for logic, not formatting html. Leave html for helper functions and the “view” portion of the script (which should be the very last thing that happens)
Keep it DRY (don’t repeat yourself). If you have methods doing the same thing, it’s time to refactor. Pass in a variable or an array for the method to work with.
—-
Further ideas relating to your comment:
The collection of the urls would typically be the job of an object. (Look into the PDO object. Helpful reference )
In all my projects, I use an object (named Database) to wrap around php’s db access, similar to pdo. It includes the following 3 methods (code is omitted for brevity):
public function prepare(string $query) { ... }
public function execute(array $params) { ... }
public function nextRecord() {...}
In a procedural script, you would first do whatever initialization is needed, deal with any user input using the PRG pattern, and any other logic. Then you would output the html, using php only to loop and insert variables. In OOP terms, this roughly corresponds to the MVC pattern (which is well worth learning).
So, for the example, let’s say that we have a database of urls:
ID URL Image
1 foo.com Image1.com
2 bar.com Image2.com
3 baz.com Image3.com
A procedural script could go as follows:
<?php
require(‘database.php’);
// optionally deal with user input
$url = new Database; // example is assuming connection is handled in the object
$url->prepare(“select url, image from sometable”);
$url->execute();
// all logic is complete; now give the output
?>
<!— html stuff —>
<ul>
<?php while($row=$url->nextRecord() ): ?>
<li><img src="<?= $row->image ?>" alt="Sponsor"/></li>
<?php endwhile; ?>
</ul>
Admittedly, I haven’t explained my object; space does not permit. But this should give you an overview of what’s possible and how to display 150 urls without repeating yourself.
Just to add to excellent answer by Tim Morton: Let's suppose, that the three links are almost always the same, then you can do something like this:
class bannClass {
private $class_varA = 'https://example.com';
private $class_varB = 'https://example.com';
private $class_varC = 'https://example.com';
public $username = '';
public function __construct($nameA = null, $nameB = null, $nameC = null) {
if (!empty($nameA)) $this->class_varA = $nameA;
if (!empty($nameB)) $this->class_varB = $nameB;
if (!empty($nameC)) $this->class_varC = $nameC;
}
public function getVarA(){
return $this->class_varA;
}
public function getVarB(){
return $this->class_varB;
}
public function getVarC(){
return $this->class_varC;
}
}
What above does, that if the class is not called with any parameters = $foo = new bannClass(); it will default all three URLs to what was set as default. Obviously, you should arrange the variables in such manner, that first is possibly changed the most time:
$bar = new bannClass('https://stackoverflow.com');
echo $bar->getVarA(); // returns stackoverflow.com
echo $bar->getVarC(); // returns example.com
Because changing only third parameter looks kinda stupid:
$baz = new bannClass(null,null,'https://stackoverflow.com');
cho $baz->getVarA(); // returns example.com
echo $baz->getVarC(); // returns stackoverflow.com
I am having some issues with my function which returns an array, I decided to try and use an OO approach to my php code and try to make a class with a few static functions since I decided I don't want to access it using an object. In my code, within the same class, I decided to make the following function:
public static function decideCategory($tweets) {
$tweet = $tweets;
if(in_array($tweet, self::$food)) {
echo "\nOur " . $tweet . " is under food\n";
} //if statements of the same nature below as well.
}
Now, this function works in the sense that it does not throw an error where $food is definded as an array at the top. However, originally I simply had $food defined at the top as just a private static variable, and then I had the following function which I passed into the in_array.
public static function getFood()
{
self::$food = array("Wendys", "McDonalds", "Wendy's", "Chic Fil A", "Chic-Fil-a", "Burger", "TGI", "BBQ", "Grilling", "Wine", "Tasty", "Yum", "IHOP", "Pancakes", "Pizza", "Cake"
,"Baking");
return self::$food;
}
However, it would return an error saying that in_array expects an array value for its second argument, but that instead it sees that a null was passed instead. Why is that and how can I use methods to do my comparison rather than the variables themselvs. If this were Java this would be how I would do it, and as such I cannot see why php would have these issues as it appears to follow a similar logic with returns.
Yes it would error because until you call self::getFood() Self::$food is null if you have declared it as
static $food;
update your method as below
public static function decideCategory($tweets)
{
$tweet = $tweets;
$food = self::getFood();
if(in_array($tweet, $food)) {
echo "\nOur " . $tweet . " is under food\n";
} //if statements of the same nature below as well.
}
I'm building an object-oriented wrapper around curl and have created a setter for the CURLOPT_ constants that stores to a $property => $value array.
public function setCurlOpt($optCode, $optValue) {
$ch = $this->ch;
curl_setopt($ch, $optCode, $optValue);
$this->curlOpts[$optCode] = $optValue;
}
$curler->setCurlOpt(CURLOPT_FOLLOWLOCATION, 1);`
However, $optCode is not a valid index for the array, since it references a resource ID instead of the name of the constant.
In order to make this work, I need to be able to get the name of the constant. Is there a way to do something along the lines of this in PHP:
function getConstantName($fromVariable) {
... return $constantName;
}
$x = CONSTANT_Y;
echo getConstantName($x);
Output: CONSTANT_Y
Once constant is assigned to variable there no way to find out which constant was used in assignment. PHP just copies constant value into variable.
Only viable option for you is to use combination of defined() and constant() and pass only option name after CURLOPT_
public function setCurlOpt($optCode, $optValue) {
if (defined("CURLOPT_" . $optCode) === true)
{
$ch = $this->ch;
curl_setopt($ch, constant("CURLOPT_" . $optCode), $optValue);
$this->curlOpts[constant("CURLOPT_" . $optCode)] = $optValue;
}
}
$curler->setCurlOpt("FOLLOWLOCATION", 1);
This is kind of a long shot, but it might be worth a try:
function getConstantName($fromVariable) {
return array_search($fromVariable, get_defined_constants(), 1);
}
I'm getting this error when I run the script
php Fatal error: Cannot redeclare class AppMailCore in /appmail.core.php on line 10
I need to make loop that will also use some variables from a class file . The code from main.php looks like this :
$iesc = 1;
while($iesc less than 5)
{
include('includes/appmail.core.php');
---
I used "less than " in the code above 'cause I don't know to unescape "<" symbold within the pre markup .
I understand that I'm not allowed to re-delcare the class but I don't know how to make the class variables run through the loop .
appmail.core.php looks like this
require_once('appmail.config.php');
require_once('helpers'.DIRECTORY_SEPARATOR.'appmail.rest.php');
class AppMailCore
{
var $AppMailRest;
var $api_key;
var $url;
/**
* Initialises AppMailCore. Optionally provide runtime api key and url.
*/
function AppMailCore($api_key = APPMAIL_API_KEY, $url = APPMAIL_URL) {
$this->url = $url;
$this->api_key = $api_key;
$this->AppMailRest = new AppMailRest($this->url);
}
/**
* Asynchronously sends an email using Google App Engine
*
* Params are fairly self explanatory. However, note that the "from" address must be a registered email with
* your Google App Engine account.
*/
function send($to, $from, $subject, $plain, $html) {
$api_key = $this->api_key;
$status = $this->AppMailRest->post('send', compact('api_key','to','from','subject','plain','html'));
return $status;
}
}
the appmail.config.php loooks like this
$app1DB = new mysqli("localhost", "root", "", "ast");
$app1RSP = $app1DB->query("SELECT app_id FROM Application WHERE emails_sent fetch_assoc();
$app_id = $app1Object['app_id'];
define('APPMAIL_API_KEY', 'JLQ7P5SnTPq7AJvLnUysJmXSeXTrhgaJ');
define('APPMAIL_URL', "http://$app_id.appspot.com/");
$app1RSP->free();
$app1DB->close();
Basically I need to get variable APPMAIL_URL/$app_id in the class on each loop run.
Why aren't you doing the include before the loop ?
Another tip: use include_once ?
Third tip: include directly appmail.config.php if you need a constant from it, not appmail.core.php ?
EDIT
Basically I need to get variable
APPMAIL_URL/$app_id in the class on
each loop run.
If its value is supposed to change through the script execution (as I just saw), then you shouldn't define it as a constant.
What I'd like to do is take the route for the current action along with any and all of the route and query string parameters, and change a single query string parameter to something else. If the parameter is set in the current request, I'd like it replaced. If not, I'd like it added. Is there a helper for something like this, or do I need to write my own?
Thanks!
[edit:] Man, I was unclear on what I actually want to do. I want to generate the URL for "this page", but change one of the variables. Imagine the page I'm on is a search results page that says "no results, but try one of these", followed by a bunch of links. The links would contain all the search parameters, except the one I would change per-link.
Edit:
Ok I got a better idea now what you want. I don't know whether it is the best way but you could try this (in the view):
url_for('foo',
array_merge($sf_request->getParameterHolder()->getAll(),
array('bar' => 'barz'))
)
If you use this very often I suggest to create your own helper that works like a wrapper for url_for.
Or if you only want a subset of the request parameters, do this:
url_for('foo',
array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
array('bar' => 'barz'))
)
(I formated the code this way for better readability)
Original Answer:
I don't know where you want to change a parameter (in the controller?), but if you have access to the current sfRequest object, this should do it:
$request->setParameter('key', 'value')
You can obtain the request object by either defining your action this way:
public function executeIndex($request) {
// ...
}
or this
public function executeIndex() {
$request = $this->getRequest();
}
For symfony 1.4 I used:
$current_uri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$uri_params = $sf_request->getParameterHolder()->getAll();
$url = url_for($current_uri.'?'.http_build_query(array_merge($uri_params, array('page' => $page))));
echo link_to($page, $url);
Felix's suggestion is good, however, it'd require you to hard core the "current route"..
You can get the name of the current route by using:
sfRouting::getInstance()->getCurrentRouteName()
and you can plug that directly in url_for, like so:
url_for(sfRouting::getInstance()->getCurrentRouteName(),
array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
array('bar' => 'barz'))
)
Hope that helps.
With the same concept than Erq, and thanks to his code, I have made the same with some small changes, since my URL needs to convert some characters. Its generic though and should work with most forms, in order to save the parameters the user has chosen to search for.
public function executeSaveFormQuery(sfWebRequest $request)
{
$sURLServer = "http://";
$sURLInternalUri = "";
$page = "";
$sURLInternalUri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$suri_params = $request->getParameterHolder()->getAll();
$sParams = http_build_query(array_merge($suri_params));
$dpos = strpos($sURLInternalUri, "?");
$sURLConsulta[$dpos] = '/';
$sURL = substr($sURLInternalUri, $dpos);
$dpos = strpos($sURL, "=");
$sURL[$dpos] = '/';
$sURLFinal = $sURLServer . $sURL . '?' . $sParams;
//$this->redirect($this->module_name . '/new');
self::executeNew($request, $sURLFinal);
//echo "var_dump(sURLFinal): ";
//var_dump($sURLFinal);
//echo "<br></br>";
//return sfView::NONE;
}
In executeNew, as easy as:
public function executeNew(sfWebRequest $request, $sURLQuery)
{
//$sURLQuery= "http://";
if ($sURLQuery!= "")
{
$this->form = new sfGuardQueryForm();
//echo "var_dump(sURLQuery)";
//var_dump($sURLQuery);
//echo "<br></br>";
$this->form->setDefault('surl', $sURLQuery);
}
else
{
$this->form = new sfGuardQueryForm();
}
}
echo $sf_context->getRequest()->getUri();