4
I have a custom class calling for ArrayList
, I created to handle objects in a small project of mine, but I’d like to abstract it further, transforming it into an interface. In this way, I could create other classes that do the same thing with different banks (in this class, saved in a txt
, but I have another that does the same things in a JSON file and in the future I will do one to save in Mysql).
How can I perform this transformation if it is feasible?
Follows the class ArrayList
class ArrayList {
private static $list = null;
private function __construct() {
}
private static function getList() {
if (!isset(self::$list)) {
$linha = "";
if (file_exists(dirname(__DIR__) . '/model/DB.txt')) {
$banco = dirname(__DIR__) . '/model/DB.txt';
$a = fopen($banco, 'r');
$linha = fread($a, filesize($banco));
self::$list = unserialize($linha);
} else {
self::$list = Array();
}
}
}
public static function add($item) {
self::getList();
self::$list[] = $item;
}
public static function remove($item) {
self::getList();
for ($i = 0; $i < self::size(); $i++) {
if (self::get($i) === $item) {
unset(self::$list[$i]);
break;
}
}
self::$list = array_values(self::$list);
}
public static function get($indice) {
self::getList();
return self::$list[$indice];
}
public static function size() {
self::getList();
return sizeof(self::$list);
}
private static function gravar() {
$texto = serialize(self::$list);
$a = fopen(dirname(__DIR__) . '/model/DB.txt', 'w');
fwrite($a, $texto);
fclose($a);
}
public static function atualizarDB() {
self::gravar();
}
}
What I’m trying to do would be something like this:
interface ArrayList{
getList();
add($item);
save();
}
I didn’t quite understand the problem, to do this just create the interface and define all methods(signatures) without implementation and then each class that implements it, will need to create code that varies between classes.
– rray
it is more practical to create an abstract class, since it has some functions that are equal regardless of implementation, such as
add
,get
,remove
andsize
– Pedro Sanção
@rray the problem is that, handling json or txt, if I change the files from different locations, the instance that is implementing the interface will not update.
– user28595