我一直在编写一个工作脚本。将Slack与PHP一起使用。在工作中我们使用CodeIgniter(悲伤的脸)所以我必须适应,我决定将我的脚本编写为库。
这里没有问题,代码不起作用,因为它工作正常,但我只是想知道如何在调用库时应用方法链,以便我和我的同事我们使用库时可以编码清理。
这是我写的图书馆 - 我更多的是程序员在培训,所以我的OOP知识有限。
<?php defined('BASEPATH') OR exit('No direct script access allowed');
include('../vendor/autoload.php');
use GuzzleHttp\Client;
class Slack {
protected $ci;
private $channel;
private $endpoint;
private $icon;
private $username;
public function __construct()
{
$this->ci =& get_instance();
$this->ci->config->load('slack');
$this->baseUri = $this->ci->config->item('base_uri');
$this->channel = $this->ci->config->item('channel');
$this->endpoint = $this->ci->config->item('endpoint');
$this->icon = $this->ci->config->item('icon');
$this->username = $this->ci->config->item('username');
$this->client = new Client([
'base_uri' => $this->baseUri
]);
}
public function getChannel()
{
return $this->channel;
}
public function setChannel($channel)
{
$this->channel = $channel;
return $this;
}
public function getEndpoint()
{
return $this->endpoint;
}
public function setEndpoint($endpoint)
{
$this->endpoint = $endpoint;
return $this;
}
public function getIcon()
{
return $this->icon;
}
public function setIcon($icon)
{
(mb_substr($icon, 0, 1) == ':')
? $this->iconType = 'icon_emoji'
: $this->iconType = 'icon_url';
$this->icon = $icon;
return $this;
}
public function getIconType()
{
return ($this->iconType) ? $this->iconType : 'icon_emoji';
}
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
return $this;
}
public function to($channel)
{
$this->setChannel($channel);
return $channel;
}
public function from($username)
{
$this->setUsername($username);
return $username;
}
public function icon($icon)
{
$this->setIcon($icon);
return $icon;
}
public function payload($text)
{
$payload = [
'channel' => $this->getChannel(),
$this->getIconType() => $this->getIcon(),
'link_names' => 1,
'text' => $text,
'username' => $this->getUsername(),
];
return $payload;
}
public function send($text)
{
$payload = json_encode($this->payload($text));
$this->client->post($this->getEndpoint(), [
'body' => $payload
]);
return $this;
}
}
现在我在我们的API中使用它,它在Controller中编码,这就是我调用方法的方法:
<?php
// ...
$this->load->library('slack');
$this->slack->icon(':hotdog:');
$this->slack->send('Hello...');
正如我所说,这很好......
我想,能够做方法链接,就像这样:
<?php
// ...
$this->slack->icon(':hotdog:')->send('Hello...');
你能告诉我这是否可行以及如何实现它?
谢谢。
答案 0 :(得分:3)
我可以看到存档您想要的内容,您只需要更改
public function icon($icon)
{
$this->setIcon($icon);
return $icon;
}
到那个
public function icon($icon)
{
$this->setIcon($icon);
return $this;
}
然后你就可以做你想做的事了
$this->slack->icon(':hotdog:')->send('Hello...');
无论如何你的图标方法不需要返回$ icon你已经有了getIcon方法 也是你的发送方法在发出请求之前调用有效负载方法,以便它可以工作