We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 26503
    • 620 Posts
    My $scriptProperties is getting cached somewhere & I have no idea how! I've been modifying the TwitterExchange library for use in modx & need to cache the results of different tags passed to the search function, but the hashtag I am searching for is getting cached in the scriptproperties, so I can't write a new cache file for each different search!

    Here is the call example I am working with [notice it's called uncached?]:

    [[!TwitterExchange? &cacheExpires=`30` &getfield=`#red` &count=`1` &tpl=`InlineTweetsTpl`]]
    
    [[!TwitterExchange? &cacheExpires=`30` &getfield=`#green` &count=`1` &tpl=`InlineTweetsTpl`]]
    
    [[!TwitterExchange? &cacheExpires=`30` &getfield=`#blue` &count=`1` &tpl=`InlineTweetsTpl`]]



    The TwitterExchange snippet:

    <?php
    $output = '';
    
    $exchange_core = $modx->getOption('core_path').'components/TwitterAPIExchange/model/';
    
    $scriptProperties['oauth_access_token'] = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
    $scriptProperties['oauth_access_token_secret'] = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
    $scriptProperties['consumer_key'] = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
    $scriptProperties['consumer_secret'] = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
    $scriptProperties['url'] = 'https://api.twitter.com/1.1/search/tweets.json';
    $scriptProperties['tpl'] = !empty($scriptProperties['tpl']) ? $scriptProperties['tpl'] : 'InlineTweetTpl';
    $scriptProperties['getfield'] = !empty($scriptProperties['getfield']) ? $scriptProperties['getfield'] : '#default';
    
    echo '<pre>';print_r($scriptProperties);echo '</pre>';
    
    $exchange = $modx->getService('twitterapiexchange', 'TwitterAPIExchange', $exchange_core, $scriptProperties);
    
    if (!$exchange instanceof TwitterAPIExchange){return 'Insantiation failed';}
    
    $output = $exchange->searchTweets();
    
    return $output;
    



    The class, constructor and function:

    <?php
    
    
    /**
     * Twitter-API-PHP : Simple PHP wrapper for the v1.1 API
     * 
     * PHP version 5.3.10
     * 
     * @category Awesomeness
     * @package  Twitter-API-PHP
     * @author   James Mallison <[email protected]>
     * @license  MIT License
     * @link     http://github.com/j7mbo/twitter-api-php
     */
    class TwitterAPIExchange
    {
        private $oauth_access_token;
        private $oauth_access_token_secret;
        private $consumer_key;
        private $consumer_secret;
        private $postfields;
        private $getfield;
        protected $oauth;
        public $url;
    
        /**
         * Create the API access object. Requires an array of settings::
         * oauth access token, oauth access token secret, consumer key, consumer secret
         * These are all available by creating your own application on dev.twitter.com
         * Requires the cURL library
         * 
         * @param array $scriptProperties
         */
    	public function __construct(modX &$modx,array $scriptProperties){
    		
    		$this->modx =& $modx;
    		
    		$this->modx->setLogLevel(xPDO::LOG_LEVEL_ERROR);
    		
    		$this->modx->setLogTarget('ECHO');
    		
    		$this->scriptProperties = $scriptProperties;
    		
    		if (!in_array('curl', get_loaded_extensions())) 
    		{
    		throw new Exception('You need to install cURL, see: http://curl.haxx.se/docs/install.html');
    		}
    		
    		if (!isset($scriptProperties['oauth_access_token'])
    			|| !isset($scriptProperties['oauth_access_token_secret'])
    			|| !isset($scriptProperties['consumer_key'])
    			|| !isset($scriptProperties['consumer_secret']))
    		{
    			throw new Exception('Make sure you are passing in the correct parameters');
    		}
    		
    		$this->oauth_access_token = $scriptProperties['oauth_access_token'];
    		$this->oauth_access_token_secret = $scriptProperties['oauth_access_token_secret'];
    		$this->consumer_key = $scriptProperties['consumer_key'];
    		$this->consumer_secret = $scriptProperties['consumer_secret'];
    		//$this->tpl = $scriptProperties['tpl'];
    		
    	}
    	
        
        
        
    	public function searchTweets(){
    		
    		
    		echo '<pre>';print_r($this->scriptProperties);echo '</pre>';
    		
    		$url = $this->scriptProperties['url'];
    		$getfield = "?q=".$this->scriptProperties['getfield']."&count=".$this->scriptProperties['count']."";
    		$requestMethod = 'GET';
    		
    		// lets find it in the cache!
    		
    		$str = 'this is the cached string grr';
    		echo 'gf ='.$this->scriptProperties['getfield'];
    		$cachename = 'twitter_'.str_replace('#', '', $this->scriptProperties['getfield']);
    		
    		if($this->modx->cacheManager->get($cachename)){
    			
    			echo $this->modx->cacheManager->get($cachename);
    		
    		}else{
    			
    			$options = array(xPDO::OPT_CACHE_KEY => 'twtterfeeds',);
    			$this->modx->cacheManager->set($cachename, $str, 60, $options);
    		}
    		
    		
    		/*
    		$qstring = $this->setGetfield($getfield);
    		$oath = $this->buildOauth($url, $requestMethod, $qstring);		
    		$json = $this->performRequest($qstring, $oath['url'], $oath['oauth']); 
    		$tweets = json_decode($json);
    		$tweets = $tweets->statuses;
    		$tweetsout = '';
    		
    		foreach($tweets as $tweet){
    
    			$tweetout = array(
    				'twtext' => $tweet->text,
    				'twscreenname' => $tweet->user->screen_name,
    				'twname' => $tweet->user->name,
    				'twimage' => $tweet->user->profile_image_url,
    				);
    				
    			$myTpl = $this->tpl;
    			$tweetsout .= $this->modx->getChunk($myTpl, $tweetout);
    			//echo 'cachetime  - '.strftime('%X').'<br />';
    
    		}
    		//echo '<pre>';print_r($tweetsout);echo'</pre>';
    		$output = $this->modx->getChunk('ResponsiveTweetWrapperTpl', array('mytweets' => $tweetsout));
    		*/
    		
    		//return $output;
    		return 'output';
    
    	}




    Finally, the output:


    Array
    (
        [cacheExpires] => 10
        [getfield] => #red
        [count] => 1
        [tpl] => InlineTweetsTpl
    )
    Array
    (
        [cacheExpires] => 10
        [getfield] => #red
        [count] => 1
        [tpl] => InlineTweetsTpl
    )
    gf =#redoutput 
    
    Array
    (
        [cacheExpires] => 20
        [getfield] => #green
        [count] => 2
        [tpl] => InlineTweetsTpl
    )
    Array
    (
        [cacheExpires] => 10
        [getfield] => #red
        [count] => 1
        [tpl] => InlineTweetsTpl
    )
    gf =#redoutput 
    
    Array
    (
        [cacheExpires] => 30
        [getfield] => #blue
        [count] => 3
        [tpl] => InlineTweetsTpl
    )
    Array
    (
        [cacheExpires] => 10
        [getfield] => #red
        [count] => 1
        [tpl] => InlineTweetsTpl
    )
    gf =#redoutput



    So you can see that the $scriptProperties echoed in the snippet is correct, but when it's echoed in the class function, it's somehow cached!?

    Completely baffled by this, does anyone know why it's doing this and how to fix it??

    This question has been answered by Bruno17. See the first response.

      *** Not just websites, we also create signage, banners, print, trade show displays and more! ***

      Sean Kimball CLP, CLS.
      Technical Director / Sr. Developer | BigBlock Studios
      ._______________________________________________.
      Bigblock Studios http://www.bigblockstudios.ca Web site design & development.
      27-1300 King Street East. Box 167 Oshawa, Ontario L1H8J4 Canada.
      phone/fax: 905-426-5525
    • discuss.answer
      • 4172
      • 5,888 Posts
      with

      $exchange = $modx->getService('twitterapiexchange', 'TwitterAPIExchange', $exchange_core, $scriptProperties);


      your class is constructed only once, so the scriptProperties are passed only at the first run to your class.

      You can try to pass new scriptProperties on each snippet-run.

      Put this part into another function:

      
      public function init($scriptProperties){
              $this->modx->setLogLevel(xPDO::LOG_LEVEL_ERROR);
               
              $this->modx->setLogTarget('ECHO');
               
              $this->scriptProperties = $scriptProperties;
               
              if (!in_array('curl', get_loaded_extensions()))
              {
              throw new Exception('You need to install cURL, see: http://curl.haxx.se/docs/install.html');
              }
               
              if (!isset($scriptProperties['oauth_access_token'])
                  || !isset($scriptProperties['oauth_access_token_secret'])
                  || !isset($scriptProperties['consumer_key'])
                  || !isset($scriptProperties['consumer_secret']))
              {
                  throw new Exception('Make sure you are passing in the correct parameters');
              }
               
              $this->oauth_access_token = $scriptProperties['oauth_access_token'];
              $this->oauth_access_token_secret = $scriptProperties['oauth_access_token_secret'];
              $this->consumer_key = $scriptProperties['consumer_key'];
              $this->consumer_secret = $scriptProperties['consumer_secret'];
              //$this->tpl = $scriptProperties['tpl'];
      }
      


      $exchange = $modx->getService('twitterapiexchange', 'TwitterAPIExchange', $exchange_core);
      $exchange->init($scriptProperties);
        -------------------------------

        you can buy me a beer, if you like MIGX

        http://webcmsolutions.de/migx.html

        Thanks!
        • 26503
        • 620 Posts
        Hmm yes - that would work. But I think the more direct thing to do would be to place the keys in system settings, process them in the constructor & pass the remaining properties to the script itself:

        $output = $exchange->searchTweets($scrtipProperties);


        So, may as well learn something here, how is it that the constructor is only run once? I assumed since the TwitterExchange tag was called 3x the whole service would be run 3x, or is the constructor persistent for the single request, i.e. it would be run again on a subsequent page?

        -thanks


        Quote from: Bruno17 at Apr 22, 2014, 01:17 AM
        with

        $exchange = $modx->getService('twitterapiexchange', 'TwitterAPIExchange', $exchange_core, $scriptProperties);


        your class is constructed only once, so the scriptProperties are passed only at the first run to your class.

        You can try to pass new scriptProperties on each snippet-run.

        Put this part into another function:

        
        public function init($scriptProperties){
                $this->modx->setLogLevel(xPDO::LOG_LEVEL_ERROR);
                 
                $this->modx->setLogTarget('ECHO');
                 
                $this->scriptProperties = $scriptProperties;
                 
                if (!in_array('curl', get_loaded_extensions()))
                {
                throw new Exception('You need to install cURL, see: http://curl.haxx.se/docs/install.html');
                }
                 
                if (!isset($scriptProperties['oauth_access_token'])
                    || !isset($scriptProperties['oauth_access_token_secret'])
                    || !isset($scriptProperties['consumer_key'])
                    || !isset($scriptProperties['consumer_secret']))
                {
                    throw new Exception('Make sure you are passing in the correct parameters');
                }
                 
                $this->oauth_access_token = $scriptProperties['oauth_access_token'];
                $this->oauth_access_token_secret = $scriptProperties['oauth_access_token_secret'];
                $this->consumer_key = $scriptProperties['consumer_key'];
                $this->consumer_secret = $scriptProperties['consumer_secret'];
                //$this->tpl = $scriptProperties['tpl'];
        }
        


        $exchange = $modx->getService('twitterapiexchange', 'TwitterAPIExchange', $exchange_core);
        $exchange->init($scriptProperties);
          *** Not just websites, we also create signage, banners, print, trade show displays and more! ***

          Sean Kimball CLP, CLS.
          Technical Director / Sr. Developer | BigBlock Studios
          ._______________________________________________.
          Bigblock Studios http://www.bigblockstudios.ca Web site design & development.
          27-1300 King Street East. Box 167 Oshawa, Ontario L1H8J4 Canada.
          phone/fax: 905-426-5525
          • 3749
          • 24,544 Posts
          Yes, the getService() call instantiates the class object (if that hasn't happened already) and keeps it handy throughout the request.

          You'd get a new object on a new request.

          Using System Settings makes sense if you want the values to persist across requests.
            Did I help you? Buy me a beer
            Get my Book: MODX:The Official Guide
            MODX info for everyone: http://bobsguides.com/modx.html
            My MODX Extras
            Bob's Guides is now hosted at A2 MODX Hosting
            • 26503
            • 620 Posts
            Thanks Bob; yes, I had rewritten it making that assumption - works perfectly now.

            oath keys, credentials etc really do belong in the system settings anyway just for securities sake.


            Quote from: BobRay at Apr 24, 2014, 05:34 PM
            Yes, the getService() call instantiates the class object (if that hasn't happened already) and keeps it handy throughout the request.

            You'd get a new object on a new request.

            Using System Settings makes sense if you want the values to persist across requests.
              *** Not just websites, we also create signage, banners, print, trade show displays and more! ***

              Sean Kimball CLP, CLS.
              Technical Director / Sr. Developer | BigBlock Studios
              ._______________________________________________.
              Bigblock Studios http://www.bigblockstudios.ca Web site design & development.
              27-1300 King Street East. Box 167 Oshawa, Ontario L1H8J4 Canada.
              phone/fax: 905-426-5525