如何以正确的方式编写以下代码以打印 return 值
How to write the below code in correct manner to print the return value
public function GetTwitter() {
# Load Twitter class
//require_once('TwitterOAuth.php');
require_once (Director::baseFolder() . '/TwitterOAuth.php');
# Create the connection
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$tweets = $twitter->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=DhakaArtSummit&count=1');
# Example output
if(!empty($tweets)) {
foreach($tweets as $tweet) {
# Access as an object
@$tweetText = $tweet["text"];
# Make links active
$tweetText = preg_replace("#(http://|(www\.))(([^\s<]{4,68})[^\s<]*)#", '<a href="http://" target="_blank"></a>', $tweetText);
# Linkify user mentions
$tweetText = preg_replace("/@(w+)/", '<a href="http://www.twitter.com/" target="_blank">@</a>', $tweetText);
# Linkify tags
$tweetText = preg_replace("/#(w+)/", '<a href="http://search.twitter.com/search?q=" target="_blank">#</a>', $tweetText);
return $tweetText;
}
}
}
我已经在 php 文件的控制器中编写了代码,并希望在 ss 文件上打印 return。
在我写的ss文件上
`<% loop GetTwitter %><p> $tweetText </p><% end_loop %>`
谁能帮我破解这个code.Any帮助被采纳
一种方法是创建一个 ArrayList
,将所有推文添加为 ArrayData
(即使在您的示例中您只 return 发送一条推文)和 return 循环要经过的 ArrayList。
代码
public function getLatestTweets() {
require_once (Director::baseFolder() . '/TwitterOAuth.php');
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$tweets = $twitter->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=DhakaArtSummit&count=1');
if(!empty($tweets)) {
$output = new ArrayList();
foreach ($tweets as &$tweet) {
$tweet['TweetText'] = $this->tweetConvert(
isset($tweet['retweeted_status']) ? $tweet['retweeted_status']['text'] : $tweet['text']
);
$output->push(new ArrayData($tweet));
}
return $output;
}
return false;
}
/**
* Function to convert links, mentions and hashtags: http://goo.gl/ciKGs
*/
function tweetConvert($tweet_string) {
$tweet_string = preg_replace("/((http(s?):\/\/)|(www\.))([\w\.]+)([a-zA-Z0-9?&%.;:\/=+_-]+)/i", "<a href='http://' target='_blank'></a>", $tweet_string);
$tweet_string = preg_replace("/(?<=\A|[^A-Za-z0-9_])@([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='http://twitter.com/' target='_blank'>[=10=]</a>", $tweet_string);
$tweet_string = preg_replace("/(?<=\A|[^A-Za-z0-9_])#([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='http://twitter.com/search?q=%23' target='_blank'>[=10=]</a>", $tweet_string);
}
模板
<% loop $LatestTweets %>
<p>$TweetText</p>
<% end_loop %>
以下是我经常在 SilverStripe 3.1 中使用的代码,用于在整个网站上获取和显示 Twitter 提要。这对你来说可能有点矫枉过正,但它可能会帮助你或其他人解决这类问题。
我将我的 Twitter 设置存储在 SiteConfig
中。为此,我将 SiteConfig
扩展为 TwitterFeedSiteConfig
DataExtension
.
TwitterFeedSiteConfig.php
class TwitterFeedSiteConfig extends DataExtension {
private static $db = array(
'TwitterConsumerKey' => 'Varchar(255)',
'TwitterConsumerSecret' => 'Varchar(255)',
'TwitterAccessToken' => 'Varchar(255)',
'TwitterAccessTokenSecret' => 'Varchar(255)',
'TwitterUsername' => 'Varchar(255)',
'TwitterTweetCount' => 'Int'
);
public function updateCMSFields(FieldList $fields) {
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterConsumerKey', 'Consumer Key'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterConsumerSecret', 'Consumer Secret'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterAccessToken', 'Access Token'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterAccessTokenSecret', 'Access Token Secret'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterUsername', 'Twitter Username'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterTweetCount', 'Tweet Count'));
}
function getLatestTweets() {
// Load tmhOAuth
require('libs/tmhOAuth.php');
require('libs/tmhUtilities.php');
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => $this->owner->TwitterConsumerKey,
'consumer_secret' => $this->owner->TwitterConsumerSecret,
'user_token' => $this->owner->TwitterAccessToken,
'user_secret' => $this->owner->TwitterAccessTokenSecret,
'curl_ssl_verifypeer' => false
));
$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => $this->owner->TwitterUsername,
'count' => $this->owner->TwitterTweetCount
));
$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);
if (!isset($tweets)) {
return false;
}
if($this->_errorCheck($tweets)){
return false;
}
$output = new ArrayList();
foreach ($tweets as &$tweet) {
$tweet['text'] = $this->tweetConvert(
isset($tweet['retweeted_status']) ? $tweet['retweeted_status']['text'] : $tweet['text']
);
$tweet['createdAgo'] = $this->relativeDate(strtotime($tweet['created_at']), false);
$output->push(new ArrayData($tweet));
}
return $output;
}
private function _errorCheck($tweets){
if(array_key_exists('errors', $tweets)){
$message = 'We have encountered '.count($tweets['errors']).' error(s): <br />';
foreach ($tweets['errors'] as $error) {
$message .= $error['message'].' Code:'.$error['code'].'<br />';
}
if(Director::isDev()){
throw new Exception($message, 1);
}
return true;
}
}
/**
* Function to convert links, mentions and hashtags: http://goo.gl/ciKGs
*/
function tweetConvert($tweet_string) {
$tweet_string = preg_replace("/((http(s?):\/\/)|(www\.))([\w\.]+)([a-zA-Z0-9?&%.;:\/=+_-]+)/i", "<a href='http://' target='_blank'></a>", $tweet_string);
$tweet_string = preg_replace("/(?<=\A|[^A-Za-z0-9_])@([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='http://twitter.com/' target='_blank'>[=12=]</a>", $tweet_string);
$tweet_string = preg_replace("/(?<=\A|[^A-Za-z0-9_])#([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='http://twitter.com/search?q=%23' target='_blank'>[=12=]</a>", $tweet_string);
return $tweet_string;
}
function relativeDate($time, $AllValues = true) {
$oneDay = 86400;
$startOfYear = mktime(0, 0, 0, 0, 0);
$times = array (
24 * 60 * 60 => 'd',
60 * 60 => 'h',
60 => 'm',
1 => 's' );
// The elapsed amount of time in seconds
$elapsed = time() - floor($time);
if ($elapsed < 1) {
return '0s';
}
else if ($time < $startOfYear) {
return date("j M y", $time);
}
else if ($elapsed >= $oneDay) {
return date("j M", $time);
}
// Loop through all of the time "constants"
foreach ($times AS $seconds => $string) {
// Get the difference
$difference = floor($elapsed / $seconds);
// Is there an actual (positive) difference?
if ($difference >= 1) {
return $difference . $string;
}
}
}
public function TenMinuteCounter() {
// Returns a new number every ten minutes
return (int)(time() / 60 / 10);
}
}
我们在 config.yml 文件中添加了这个扩展。
config.yml
SiteConfig:
extensions:
- TwitterFeedSiteConfig
我在包含文件夹中创建了一个模板。然后当我想在我的模板中使用它时,我调用 <% include LatestTweets %>
。我还缓存了 LatestTweets
,因为它调用了外部服务器,这对页面加载造成了相当大的延迟。所以我放入了一个 10 分钟计数器来缓存推文 10 分钟。
LatestTweets.ss
<% cached 'LatestTweets', $SiteConfig.TenMinuteCounter %>
<% if $SiteConfig.LatestTweets %>
<div class="latestTweets">
<% loop $SiteConfig.LatestTweets %>
<div class="tweet">
<p class="tweetText">$text</p>
<div class="tweetDate">
<a href="http://twitter.com/$user.screen_name/statuses/$id_str" title="View this tweet on Twitter" target="_blank" rel="nofollow">$createdAgo</a>
</div>
</div>
<% end_loop %>
</div>
<% end_if %>
<% end_cached %>
public function GetTwitter() {
# Load Twitter class
//require_once('TwitterOAuth.php');
require_once (Director::baseFolder() . '/TwitterOAuth.php');
# Create the connection
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$tweets = $twitter->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=DhakaArtSummit&count=1');
# Example output
if(!empty($tweets)) {
foreach($tweets as $tweet) {
# Access as an object
@$tweetText = $tweet["text"];
# Make links active
$tweetText = preg_replace("#(http://|(www\.))(([^\s<]{4,68})[^\s<]*)#", '<a href="http://" target="_blank"></a>', $tweetText);
# Linkify user mentions
$tweetText = preg_replace("/@(w+)/", '<a href="http://www.twitter.com/" target="_blank">@</a>', $tweetText);
# Linkify tags
$tweetText = preg_replace("/#(w+)/", '<a href="http://search.twitter.com/search?q=" target="_blank">#</a>', $tweetText);
return $tweetText;
}
}
}
我已经在 php 文件的控制器中编写了代码,并希望在 ss 文件上打印 return。 在我写的ss文件上
`<% loop GetTwitter %><p> $tweetText </p><% end_loop %>`
谁能帮我破解这个code.Any帮助被采纳
一种方法是创建一个 ArrayList
,将所有推文添加为 ArrayData
(即使在您的示例中您只 return 发送一条推文)和 return 循环要经过的 ArrayList。
代码
public function getLatestTweets() {
require_once (Director::baseFolder() . '/TwitterOAuth.php');
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$tweets = $twitter->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=DhakaArtSummit&count=1');
if(!empty($tweets)) {
$output = new ArrayList();
foreach ($tweets as &$tweet) {
$tweet['TweetText'] = $this->tweetConvert(
isset($tweet['retweeted_status']) ? $tweet['retweeted_status']['text'] : $tweet['text']
);
$output->push(new ArrayData($tweet));
}
return $output;
}
return false;
}
/**
* Function to convert links, mentions and hashtags: http://goo.gl/ciKGs
*/
function tweetConvert($tweet_string) {
$tweet_string = preg_replace("/((http(s?):\/\/)|(www\.))([\w\.]+)([a-zA-Z0-9?&%.;:\/=+_-]+)/i", "<a href='http://' target='_blank'></a>", $tweet_string);
$tweet_string = preg_replace("/(?<=\A|[^A-Za-z0-9_])@([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='http://twitter.com/' target='_blank'>[=10=]</a>", $tweet_string);
$tweet_string = preg_replace("/(?<=\A|[^A-Za-z0-9_])#([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='http://twitter.com/search?q=%23' target='_blank'>[=10=]</a>", $tweet_string);
}
模板
<% loop $LatestTweets %>
<p>$TweetText</p>
<% end_loop %>
以下是我经常在 SilverStripe 3.1 中使用的代码,用于在整个网站上获取和显示 Twitter 提要。这对你来说可能有点矫枉过正,但它可能会帮助你或其他人解决这类问题。
我将我的 Twitter 设置存储在 SiteConfig
中。为此,我将 SiteConfig
扩展为 TwitterFeedSiteConfig
DataExtension
.
TwitterFeedSiteConfig.php
class TwitterFeedSiteConfig extends DataExtension {
private static $db = array(
'TwitterConsumerKey' => 'Varchar(255)',
'TwitterConsumerSecret' => 'Varchar(255)',
'TwitterAccessToken' => 'Varchar(255)',
'TwitterAccessTokenSecret' => 'Varchar(255)',
'TwitterUsername' => 'Varchar(255)',
'TwitterTweetCount' => 'Int'
);
public function updateCMSFields(FieldList $fields) {
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterConsumerKey', 'Consumer Key'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterConsumerSecret', 'Consumer Secret'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterAccessToken', 'Access Token'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterAccessTokenSecret', 'Access Token Secret'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterUsername', 'Twitter Username'));
$fields->addFieldToTab('Root.TwitterFeed', TextField::create('TwitterTweetCount', 'Tweet Count'));
}
function getLatestTweets() {
// Load tmhOAuth
require('libs/tmhOAuth.php');
require('libs/tmhUtilities.php');
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => $this->owner->TwitterConsumerKey,
'consumer_secret' => $this->owner->TwitterConsumerSecret,
'user_token' => $this->owner->TwitterAccessToken,
'user_secret' => $this->owner->TwitterAccessTokenSecret,
'curl_ssl_verifypeer' => false
));
$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => $this->owner->TwitterUsername,
'count' => $this->owner->TwitterTweetCount
));
$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);
if (!isset($tweets)) {
return false;
}
if($this->_errorCheck($tweets)){
return false;
}
$output = new ArrayList();
foreach ($tweets as &$tweet) {
$tweet['text'] = $this->tweetConvert(
isset($tweet['retweeted_status']) ? $tweet['retweeted_status']['text'] : $tweet['text']
);
$tweet['createdAgo'] = $this->relativeDate(strtotime($tweet['created_at']), false);
$output->push(new ArrayData($tweet));
}
return $output;
}
private function _errorCheck($tweets){
if(array_key_exists('errors', $tweets)){
$message = 'We have encountered '.count($tweets['errors']).' error(s): <br />';
foreach ($tweets['errors'] as $error) {
$message .= $error['message'].' Code:'.$error['code'].'<br />';
}
if(Director::isDev()){
throw new Exception($message, 1);
}
return true;
}
}
/**
* Function to convert links, mentions and hashtags: http://goo.gl/ciKGs
*/
function tweetConvert($tweet_string) {
$tweet_string = preg_replace("/((http(s?):\/\/)|(www\.))([\w\.]+)([a-zA-Z0-9?&%.;:\/=+_-]+)/i", "<a href='http://' target='_blank'></a>", $tweet_string);
$tweet_string = preg_replace("/(?<=\A|[^A-Za-z0-9_])@([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='http://twitter.com/' target='_blank'>[=12=]</a>", $tweet_string);
$tweet_string = preg_replace("/(?<=\A|[^A-Za-z0-9_])#([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='http://twitter.com/search?q=%23' target='_blank'>[=12=]</a>", $tweet_string);
return $tweet_string;
}
function relativeDate($time, $AllValues = true) {
$oneDay = 86400;
$startOfYear = mktime(0, 0, 0, 0, 0);
$times = array (
24 * 60 * 60 => 'd',
60 * 60 => 'h',
60 => 'm',
1 => 's' );
// The elapsed amount of time in seconds
$elapsed = time() - floor($time);
if ($elapsed < 1) {
return '0s';
}
else if ($time < $startOfYear) {
return date("j M y", $time);
}
else if ($elapsed >= $oneDay) {
return date("j M", $time);
}
// Loop through all of the time "constants"
foreach ($times AS $seconds => $string) {
// Get the difference
$difference = floor($elapsed / $seconds);
// Is there an actual (positive) difference?
if ($difference >= 1) {
return $difference . $string;
}
}
}
public function TenMinuteCounter() {
// Returns a new number every ten minutes
return (int)(time() / 60 / 10);
}
}
我们在 config.yml 文件中添加了这个扩展。
config.yml
SiteConfig:
extensions:
- TwitterFeedSiteConfig
我在包含文件夹中创建了一个模板。然后当我想在我的模板中使用它时,我调用 <% include LatestTweets %>
。我还缓存了 LatestTweets
,因为它调用了外部服务器,这对页面加载造成了相当大的延迟。所以我放入了一个 10 分钟计数器来缓存推文 10 分钟。
LatestTweets.ss
<% cached 'LatestTweets', $SiteConfig.TenMinuteCounter %>
<% if $SiteConfig.LatestTweets %>
<div class="latestTweets">
<% loop $SiteConfig.LatestTweets %>
<div class="tweet">
<p class="tweetText">$text</p>
<div class="tweetDate">
<a href="http://twitter.com/$user.screen_name/statuses/$id_str" title="View this tweet on Twitter" target="_blank" rel="nofollow">$createdAgo</a>
</div>
</div>
<% end_loop %>
</div>
<% end_if %>
<% end_cached %>