我有一个基础控制器,其中包含一种方法来向我的视图返回 Twitter 消息源。
我想将其从页面视图中移动到默认的 blade 视图中,以减少冗余,因为它将在整个站点上显示。如何从基础控制器传递数据到 blade?
我可以通过以下方式从页面控制器将其发送到视图:
我希望能够在default.blade.php和我的Base_Controller中完成所有这些操作:
我想将其从页面视图中移动到默认的 blade 视图中,以减少冗余,因为它将在整个站点上显示。如何从基础控制器传递数据到 blade?
我可以通过以下方式从页面控制器将其发送到视图:
public function get_index()
{
..................
$this->layout->nest('content', 'home.index', array(
'tweets' => $this->get_tweet()
));
}
然后在视图中,像这样输出:
if ($tweets)
{
foreach ($tweets as $tweet)
{
..............
我希望能够在default.blade.php和我的Base_Controller中完成所有这些操作:
<?php
class Base_Controller extends Controller {
/**
* Catch-all method for requests that can't be matched.
*
* @param string $method
* @param array $parameters
* @return Response
*/
public function __call($method, $parameters)
{
return Response::error('404');
}
public function get_tweet()
{
...........
return $tweets;
}
}
这怎么可能实现呢?
//////////////////////更新/////////////////////////////
应用程序/models/tweets.php
<?php
class Tweets {
public static function get($count = 3)
{
Autoloader::map(array(
'tmhOAuth' => path('app').
'libraries/tmhOAuth-master/tmhOAuth.php',
'tmhUtilities' => path('app').
'libraries/tmhOAuth-master/tmhUtilities.php'
));
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'xxx',
'consumer_secret' => 'xxx',
'user_token' => 'xxxxx',
'user_secret' => 'xxxxx',
'curl_ssl_verifypeer' => false
));
$code = $tmhOAuth->request('GET',
$tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'xxx',
'count' => $count
));
$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);
return $tweets;
}
}
application/views/widgets/tweets.blade.php
@foreach ($tweets)
test
@endforeach
application/views/layouts/default.blade.php
....
{{ $tweets }}
....
application/composers.php
<?php
View::composer('widgets.tweets', function($view)
{
$view->tweets = Tweets::get();
});
View::composer('layouts.default', function($view)
{
$view->nest('tweets', 'widgets.tweets');
});
application/controllers/base.php
<?php
class Base_Controller extends Controller {
/**
* Catch-all method for requests that can't be matched.
*
* @param string $method
* @param array $parameters
* @return Response
*/
public $layout = 'layouts.default';
public function __call($method, $parameters)
{
return Response::error('404');
}
}
application/controllers/home.php
<?php
class Home_Controller extends Base_Controller {
public $layout = 'layouts.default';
public $restful = true;
public function get_index()
{
Asset::add('modernizr', 'js/thirdparty/modernizr.js');
Asset::add('jquery',
'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
Asset::add('scripts', 'js/scripts.js');
$this->layout->title = 'title';
$this->layout->nest('content', 'home.index', array(
//'data' => $some_data
));
}
}
出现了错误:
未定义变量:tweets