function fbPageCounter()
{
$link = "https://graph.facebook.com/google?fields=name,likes&access_token=ID|SECRET";
$gData = file_get_contents($link);
$gData = json_decode($gData);
return $gData;
}
Without it being in a function I can echo it like this: $fbData->{'likes'}
Since it is now into a function, how do I echo the likes data?
UPDATE:
I'd like to know how to return the data by echoing it with the function like so: echo fbPageCounter(); not sure what goes inside to return the likes or name..
For a dynamic approach capable of accessing multiple properties, perhaps a nice solution is a class? Might be overkill but depending on what you need it to do, might not be?
class FbPageCounter {
// Stores json data from FB
public $gData;
// Set $gData
public function __construct() {
$link = "https://graph.facebook.com/google?fields=name,likes&access_token=ID|SECRET";
$gData = file_get_contents($link);
$this->gData = json_decode($gData);
}
// Returns likes
public function getLikes() {
return $this->gData->{'likes'};
}
// Returns name
public function getName() {
return $this->gData->{'name'};
}
}
$n = new FbPageCounter();
echo $n->getLikes();
echo $n->getName();
Related
Can something like this be done? I want to pass a variable from a public function to my view.
public function index() {
$home_data['username'] = "myname";
$home_data['cool'] = $this->variable;
$this->load->view('home_view', $home_data);
}
public function a_function() {
public $variable = "cool";
}
//EDIT//
This is what I m actually trying to accomplish and I m stuck.
get_two gets two items from a table. I want to add the two items to two variables and pass them to the view.
public function get_two() {
$get_results = $this->home_model->get_two_brands();
if($get_results != false){
$html = '';
foreach($get_results as $result){
$html .= '<li>'.$result->brand.'</li>';
}
$result = array('status' => 'ok', 'content' => $html);
header('Content-type: application/json');
echo json_encode($result);
exit();
}
}//public function get_two() {
Should I create two functions like this? But I don't know how to pass the $get_results array from get_two to the below functions. I tried public $get_results = $this->model ... etc but that didn't work.
public function result_one() {
return $resultOne = $get_results[0];
}
public function result_two() {
return $resultTwo = $get_results[1];
}
I'm not sure I've got the question correctly but what you're trying to achieve is something like this?
public function index() {
$home_data['username'] = "myname";
$home_data['cool'] = $this->a_function();
$this->load->view('home_view', $home_data);
}
public function a_function() {
return $variable = "cool";
}
/** AFTER EDIT **/
Things get complicated (possibly because of my english comprehension).
you said
get_two gets two items from a table. I want to add the two items to two variables and pass them to the view.
So from the function get_two() you need to get and use the result in this way?
public function index() {
$home_data['username'] = "myname";
$home_data['cool'] = $this->get_two(); // <- here?
$this->load->view('home_view', $home_data);
}
So you can try with:
public function get_two() {
$get_results = $this->home_model->get_two_brands();
if($get_results != false){
return $get_results;
}
}
and then
public function index() {
$home_data['username'] = "myname";
$home_data['cool'] = $this->get_two();
$this->load->view('home_view', $home_data);
}
and inside you home_view :
<?php
foreach($home_data['cool'] as $result){
echo '<li>'.$result->brand.'</li>';
}
?>
/** AFTER NEW QUESTION **/
I need the ids of the two choices as two distinct variables
So change the index function this way:
public function index() {
$home_data['username'] = "myname";
$home_data['cool'] = $this->get_two(); // <- maybe you don't need this anymore
list($result1, $result2) = $this->get_two();
$home_data['resultId1'] = $result1->id;
$home_data['resultId2'] = $result2->id;
$this->load->view('home_view', $home_data);
}
Now you're able to use $home_data['resultId1'] and $home_data['resultId1'] inside your view.
You can also define the variable in the constructor, this is one way .
CODE:
public function __construct(){
$this->variable = "cool";
}
public function index() {
$home_data['username'] = "myname";
$home_data['cool'] = $this->variable;
$this->load->view('home_view', $home_data);
}
I don't know the codeigniter framework so this is why I asked for a part of your view but it looks pretty simple as I check in the doc. And the doc's are not bad there.
Check for Adding Dynamic Data to the View
public_function() should return something, for ex:
function public_function() {
return 'groovy';
}
Then call it in the controller:
public function index() {
$home_data['username'] = "myname";
$home_data['cool'] = $this->public_function();
$this->load->view('home_view', $home_data);
}
Then add to the view somewhere
<?php echo $home_data['cool'];?>
I assume it's wrapped in some class. So if you cannot return the value you need (for ex. function already returns something else) then do something like this:
class Someclass {
public $some_class_variable;
function public_function() {
$this->some_class_variable = 'groovy';
}
function index() {
$home_data['cool'] = $this->some_class_variable;
}
}
I am working with lemonade-php. My code is at https://github.com/sofadesign/limonade.
The issue I am having is when I try to run
class syscore {
public function hello(){
set('post_url', params(0));
include("./templates/{$this->temp}/fullwidth.tpl");
return render('fullwidth');
}
}
which then loads the fullwidth.tpl and runs function fullwidth
fullwidth.tpl
<?php
global $post;
function fullwidth($vars){
extract($vars);
$post = h($post_url);
}
print_r($this->post($post));
?>
it seems to pass the $post_url but I can not pass it again to the print_r($this->post($post));
However when I try to run print_r($this->post($post)) inside the fullwidth function it says it can not find the post() function
I have tried a number of things like below
function fullwidth($vars){
extract($vars);
$post = h($post_url);
print_r(post($post));
}
I tried re connecting to the syscore by
$redi = new syscore();
$redi->connection() <-- this works
$redi->post($post) <-- this does not
Here is my full class syscore
class syscore {
// connect
public function connect($siteDBUserName,$siteDBPass,$siteDBURL,$siteDBPort, $siteDB,$siteTemp){
for ($i=0; $i<1000; $i++) {
$m = new Mongo("mongodb://{$siteDBUserName}:{$siteDBPass}#{$siteDBURL}:{$siteDBPort}", array("persist" => "x", "db"=>$siteDB));
}
// select a database
$this->db = $m->$siteDB;
$this->temp = $siteTemp;
}
public function hello(){
set('post_url', params(0));
include("./templates/{$this->temp}/fullwidth.tpl");
return render('fullwidth');
}
public function menu($data)
{
$this->data = $data;
$collection = $this->db->redi_link;
// find everything in the collection
//print $PASSWORD;
$cursor = $collection->find(array("link_active"=> "1"));
if ($cursor->count() > 0)
{
$fetchmenu = array();
// iterate through the results
while( $cursor->hasNext() ) {
$fetchmenu[] = ($cursor->getNext());
}
return $fetchmenu;
}
else
{
var_dump($this->db->lastError());
}
}
public function post($data)
{
$this->data = $data;
$collection = $this->db->redi_posts;
// find everything in the collection
//print $PASSWORD;
$cursor = $collection->find(array("post_link"=> $data));
if ($cursor->count() > 0)
{
$posts = array();
// iterate through the results
while( $cursor->hasNext() ) {
$posts[] = ($cursor->getNext());
}
return $posts;
}
else
{
var_dump($this->db->lastError());
}
}
}
It looks like you are having some issues understanding the execution path that PHP is taking when trying to render your template. Let's take a more in-depth look, shall we?
// We're going to call "syscore::hello" which will include a template and try to render it
public function hello(){
set('post_url', params(0)); // set locals for template
include("./templates/{$this->temp}/fullwidth.tpl"); // include the template
return render('fullwidth'); // Call fullwidth(array('post_url' => 'http://example.com/path'))
}
The trick to solving this one is to understand how PHP include works. When you call include("./templates/{$this->temp}/fullwidth.tpl") some of your code is executing in the scope of the syscore object, namely:
global $post;
and
print_r($this->post($post));
fullwidth is created in the global scope at this point, but has not yet been called. When render calls fullwidth you're no longer in the syscore scope, which is why you cannot put $this->post($post) inside without triggering an error.
Ok, so how do we solve it? Glad you asked.
We could probably refactor syscore::post to be a static method, but that would then require syscore::db to be static, and always return the SAME mongodb instance (singleton pattern). You definitely do not want to be creating 1000 Mongo instances for each syscore instance.
We could just abuse the framework. A much poorer solution, but it will get the job done.
fullwidth.tpl
<?php
function fullwidth($vars){
$post_url = ''; // put the variables you expect into the symbol table
extract($vars, EXTR_IF_EXISTS); // set EXTR_IF_EXISTS so you control what is added.
$syscore_inst = new syscore;
$post = h($post_url);
print_r($syscore->post($post)); // I think a puppy just died.
}
Look the second way is a complete hack, and writing code like that will probably mean you won't get promoted. But it should work.
But let's say you wanted to get promoted, you would make good, shiny code.
// Note: Capitalized class name
class Syscore {
protected static $_db;
public static function db () {
if (! static::$_db) {
static::$_db = new Mongo(...);
}
return static::$_db;
}
// #FIXME rename to something more useful like "find_posts_with_link"
public static post($url) {
$collection = static::db()->redi_posts;
// find everything in the collection
$cursor = $collection->find(array("post_link"=> $url));
// Changed to a try-catch, since we shouldn't presume an empty find is
// an error.
try {
$posts = array();
// iterate through the results
while( $cursor->hasNext() ) {
$posts[] = ($cursor->getNext());
}
return $posts;
} catch (Exception $e) {
var_dump($this->db->lastError());
}
}
}
Then in your fullwidth function, we don't have to do any of that stupid nonsense of treating an instance method like it were a static method.
function fullwidth($vars){
$post_url = ''; // put the variables you expect into the symbol table
extract($vars, EXTR_IF_EXISTS); // set EXTR_IF_EXISTS so you control what is added.
$post = h($post_url);
print_r(Syscore::post($post)); // static method. \O/ Rainbows and unicorns.
}
I'm working on a class that will count twitter reactions to a link and also display them.
Currently I'm working on the counting portion and my count always equals 0 even though the array created in the constructor has multiple elements.
Any help would be appreciated. Thanks.
<?php
class TwitterReactions{
function __construct($url){
if($url){
$output=array();
$query = 'http://search.twitter.com/search.json?q='.$url;
$reactions=file_get_contents($query);
$reactions_array=json_decode($reactions, TRUE);
foreach($reactions_array as $results){
foreach($results as $result){
$output['user'][]=$result['from_user'];
$output['image'][]=$result['profile_image_url'];
$output['message'][]=$result['text'];
$output['date'][]=$result['created_at'];
}
}
return $output['user'];
} else {
echo "<p>Please provide a url...</p>";
}
}
function count_reactions($output){
//print_r($output);
$count = count($output['user']);
return $count;
}
}
?>
I agree with some of what Aliaksandr Astashenkau has in his answer but there are still some problems with the class.
It looks to me as if your initial problem was that you were expecting the __construct to return $output and you were then passing the object that you created into the count_reactions() method. Something like this...
$twitter = new TwitterReactions($url);
$count = $twitter->count_reactions($twitter);
You don't have your call to the count_reactions() method posted so this is just a hunch. If that's how you were using it the constructor it isn't meant to be used that way. Constructors always return a new instance of the class. You cannot return any other type of value from a constructor. You cannot use the return keyword in the __construct method.
As Aliaksandr Astashenkau points out $output should be a class member. I would also make $count a class member. In this case there's not much of a point of making either private so you don't really need accessor methods either but you can include them if you want.
I would make the class something like this...
<?php
class TwitterReactions
{
public $url = '';
public $output = array();
public $count = 0;
function __construct($url)
{
$this->url = $url;
$query = 'http://search.twitter.com/search.json?q='.$url;
$reactions=file_get_contents($query);
$reactions_array=json_decode($reactions, TRUE);
foreach($reactions_array as $results)
{
foreach($results as $key => $result)
{
// I find it easier if the data is arranged by each tweet but you can keep the array structure how you have it.
$this->output[$key]['user'] = $result['from_user'];
$this->output[$key]['image'] = $result['profile_image_url'];
$this->output[$key]['message'] = $result['text'];
$this->output[$key]['date'] = $result['created_at'];
}
}
$this->count = count($this->output);
}
}
You could then use the class like this
$twitter = new TwitterReactions($url);
// you now have access to output directly
$twitter->output;
// and count
$twitter->count;
Anyhow there are many ways to accomplish the same thing but I hop this helps give you some ideas.
You probably want to make an $output array to be a property of your class. Then $this->output would be availbale in count_reactions method.
<?php
class TwitterReactions {
public $output;
function __construct($url){
if($url){
$output=array();
$query = 'http://search.twitter.com/search.json?q='.$url;
$reactions=file_get_contents($query);
$reactions_array=json_decode($reactions, TRUE);
foreach($reactions_array as $results){
foreach($results as $result){
$output['user'][]=$result['from_user'];
$output['image'][]=$result['profile_image_url'];
$output['message'][]=$result['text'];
$output['date'][]=$result['created_at'];
}
}
$this->output = $output;
return $output['user'];
} else {
echo "<p>Please provide a url...</p>";
}
}
function count_reactions($output){
//print_r($this->output);
$count = count($this->output['user']);
return $count;
}
}
class Assignation {
private $VVal_1 = 1;
private $VNam_1 = "One";
//....Multiple Items
private $VVal_2000 = 2000; //For Example
private $VNam_2000 = "Two Thousands"; //For Example
private static $Hash = array(); //How to initialize???
private static function Assigning(){
//This function for to assign the array elements (initialize)
global $Hash;
$this->Hash = array(); //to empty Hash variable and not add more data than it should.
$this->Hash[$this->VVal_1] = $this->VNam_1;
//....Multiple Items
$this->Hash[$this->VVal_2000] = $this->VNam_2000;
}
public static function GetVal($Nam) {
$this->Assigning(); //or use self::Assigning(); //I want to avoid this call
if (array_search($Nam, $this->Hash))
return array_search($Nam, $this->Hash);
return -1;//error
}
public static function GetNam($Val) {
$this->Assigning(); //or use self::Assigning(); //I want to avoid this call
if (array_key_exists($Val, $this->Hash))
return $this->Hash[$Val];
return "Error";
}
}
Class Testing {
static $OtherVal = Assignation::GetVal("BLABLA"); //for example
static $OtherNam = Assignation::GetNam(20); //for example
//Other functions...
}
Hi, you can see my script or code php...
I need to initialize the Hash array, this have static word because I need to use it in other static function. And this "other function" need to use it for other static variable...
I need to know how to implement it the right way..
Thanks chep.-.
<?php
echo "pre-Class Assignation<br/>";
class Assignation {
private $VVal_1 = 1;
private $VNam_1 = "One";
private $VVal_2K = 2000;
private $VNam_2K = "Two Thousands";
private static $Hash = array();
private static function Assigning(){
if(!empty(self::$Hash)) return;
self::$Hash[$this->VVal_1] = $this->VNam_1;
self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}
public static function GetVal($Nam) {
self::Assigning();
if (array_search($Nam, self::$Hash)) return array_search($Nam, self::$Hash);
return -1;//error
}
public static function GetNam($Val) {
self::Assigning();
if (array_key_exists($Val, self::$Hash)) return self::$Hash[$Val];
return "Error";
}
}
echo "post-Class Testing<br/>";
echo Assignation::GetVal("BLABLA");
echo "post-Class Mid<br/>";
echo Assignation::GetNam(20);
echo "post-Class Sample<br/>";
//Testing::MyPrint();
?>
This code is not running, somebody help me testing the code...
result:
pre-Class Assignation
post-Class Assignation
post-Class Testing
that mean:
" echo Assignation::GetVal("BLABLA");"
have error...
In Assigning(), try using self::$Hash rather than $this->Hash and remove the global $Hash. Same applies for calling Assigning(): self::Assigning() as your comments suggest.
$this references the current object, so you must use self:: for all static functions and member data when inside the class.
Also, if this is your real code and not just a sample, you may want to check whether you have already done initialization, otherwise you will be doing it for every call to GetVal() and GetNam(). You could do this by adding something like if(!empty(self::$Hash)) return at the beginning of Assigning()
EDIT
private static function Assigning() {
if(!empty(self::$Hash)) return; // already populated
self::$Hash = array();
self::$Hash[$this->VVal_1] = $this->VNam_1;
//....Multiple Items
self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}
Basically, what I want to do is create a class called Variables that uses sessions to store everything in it, allowing me to quickly get and store data that needs to be used throughout the entire site without working directly with sessions.
Right now, my code looks like this:
<?php
class Variables
{
public function __construct()
{
if(session_id() === "")
{
session_start();
}
}
public function __set($name,$value)
{
$_SESSION["Variables"][$name] = $value;
}
public function __get($name)
{
return $_SESSION["Variables"][$name];
}
public function __isset($name)
{
return isset($_SESSION["Variables"][$name]);
}
}
However, when I try to use it like a natural variable, for example...
$tpl = new Variables;
$tpl->test[2] = Moo;
echo($tpl->test[2]);
I end up getting "o" instead of "Moo" as it sets test to be "Moo," completely ignoring the array. I know I can work around it by doing
$tpl->test = array("Test","Test","Moo");
echo($tpl->test[2]);
but I would like to be able to use it as if it was a natural variable. Is this possible?
You'll want to make __get return by reference:
<?php
class Variables
{
public function __construct()
{
if(session_id() === "")
{
session_start();
}
}
public function __set($name,$value)
{
$_SESSION["Variables"][$name] = $value;
}
public function &__get($name)
{
return $_SESSION["Variables"][$name];
}
public function __isset($name)
{
return isset($_SESSION["Variables"][$name]);
}
}
$tpl = new Variables;
$tpl->test[2] = "Moo";
echo($tpl->test[2]);
Gives "Moo".