INFRA

cakePHP2.3 TwitterKit Plugin

https://github.com/elstc/twitter_kit/tree/2.0

database.phpにコンシューマキーなどの設定を書く

public $twitter = array(
'datasource' => 'TwitterKit.TwitterSource',
'oauth_consumer_key' => 'CAIFwaaaaaaaaaa80qZBMQ',
'oauth_consumer_secret' => 'GaJeqgkiB31taaaaaaaaaaa7aofseascV4kWNMMuE',
'oauth_callback' => '/twitter_kit/oauth/callback/',
);

twitter_usersテーブルを作成する

./cake schema create -p TwitterKit

コントローラの$componentsに、‘TwitterKit.Twitter’を追加する

public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'posts', 'action' => 'index'),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'mail')
),
),
),
'TwitterKit.Twitter'
);

コントローラーにログイン、ログアウトメソッドをつくる

public function login(){
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
$this->set_twitter_options();
}
/**
* twitterログイン用オプションのセット
*/
private function set_twitter_options(){
$linkOptions = array();
if (!empty($this->params['named']['datasource'])) {
$linkOptions['datasource'] = $this->params['named']['datasource'];
}
if (!empty($this->params['named']['authenticate'])) {
$linkOptions['authenticate'] = $this->params['named']['authenticate'];
}
$linkOptions['loading'] = 'Loading...';
$linkOptions['login'] = 'twitterでログイン';
$this->set('linkOptions', $linkOptions);
}
public function logout(){
$this->redirect($this->Auth->logout());
}

コントローラーでJsヘルパーと、Twitterヘルパーを読み込む

public $helpers = array('Js', 'TwitterKit.Twitter');

ビュー(users/login.ctp)をつくる

<p><?php echo $this->Session->flash('auth'); ?></p>
<?php if (!$this->Session->check('Auth.User')):?>
<div>
<?php echo $this->Form->create('User', array('inputDefaults' => array('label' => false))); ?>
<table>
<tr>
<th>ユーザーID</th>
<td><?php echo $this->Form->input('mail');?></td>
</tr>
<tr>
<th>パスワード</th>
<td><?php echo $this->Form->input('password');?></td>
</tr>
</table>
<?php echo $this->Form->end(__('Login')); ?>
</div>
<p><?php echo $this->Html->link('Do you forget a password?', array('controller' => 'users', 'action' => 'pass_forget'))?></p>
<?php echo $this->Twitter->oauthLink($linkOptions); ?>
<?php echo $this->Twitter->Js->writeBuffer(); ?>
<?php else:?>
<?php echo $this->Html->link('Logout', array('controller' => 'users', 'action' => 'logout'))?>
<?php endif; ?>