0
I’m having trouble with code repetition in my CURL connection class, the class is being declared as follows:
<?php
if (!defined("ROOT_PATH")) define("ROOT_PATH", dirname(__FILE__, 2));
require_once ROOT_PATH."/helpers/Helper.php";
class PhabricatorModel
{
const TOKEN = "api.token=api-...";
public function add($parameters)
{
$channel = curl_init();
curl_setopt($channel, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
curl_setopt($channel, CURLOPT_URL, "https://pb-dc.com/api/maniphest.edit");
curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($channel, CURLOPT_POSTFIELDS, self::TOKEN.$parameters);
curl_setopt($channel, CURLOPT_POST, 1);
$result = curl_exec($channel);
if (curl_errno($channel)) {
return false;
}
curl_close($channel);
return $result;
}
public function consultProject($project)
{
$channel = curl_init();
curl_setopt($channel, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
curl_setopt($channel, CURLOPT_URL, "https://pb-dc.com/api/project.query");
curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($channel, CURLOPT_POSTFIELDS, self::TOKEN."names[]=".$project);
curl_setopt($channel, CURLOPT_POST, 1);
$result = Helper::convert_array(json_decode(curl_exec($channel)));
if (curl_errno($channel)) {
return false;
}
curl_close($channel);
return $result;
}
public function consultStory($story)
{
$channel = curl_init();
curl_setopt($channel, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
curl_setopt($channel, CURLOPT_URL, "https://pb-dc.com/api/maniphest.query");
curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($channel, CURLOPT_POSTFIELDS, self::TOKEN."status=status-open&fullText=".$story);
curl_setopt($channel, CURLOPT_POST, 1);
$result = Helper::convert_array(json_decode(curl_exec($channel)));
if (curl_errno($channel)) {
return false;
}
curl_close($channel);
return $result;
}
}
If you notice the same item from curl_init
in the 3 methods and I wanted to remove this repetition, not only in the curl_init
but also in other parts.
most cases Curl does not result in anything if you do not use
CURLOPT_SSL_VERIFYPEER, false
. I have basic knowledge. maybe that’s it– user94336
@William did not understand very well what you wanted to pass me, could explain me more ?
– Ikaro Sales
Your three methods are very similar in structure, you could make a unique method and use the switch/case structure to treat parts that are different.
– Giovanni Nunes
@Giovanninunes the idea is that over time this code is evolved, and for reading and understanding a switch/ case would not be cool for this.
– Ikaro Sales
Create a new method for startup, like this
$channel
will turn$this->channel
and put there CURLOPT_HTTPHEADER, CURLOPT_RETURNTRANSFER and CURLOPT_POST which are equal in the three cases (but you can still change them within the method whenever you need). I’m going to put an example of this here in the answers.– Giovanni Nunes