jeudi 11 avril 2019

CSV class how to connect with model class

I Have a CSV class that reads, writes CSV files. I Have a model class User and I want a method that returns me a User object from the CSV by ID (getUserById); So the CSV should return a User class object. The problem is that I want that the CSV returns also Book objects when it is called from a Book object.

I read about DI and reflection but I can't understand how to use it.

class User
{
    private $firstname;
    private $lastname;
    private $username;
    private $password;

    public function __construct($firstname, $lastname, $username, $password)
    {
        $this->firstname = $firstname;
        $this->lastname = $lastname;
        $this->username = $username;
        $this->password = $password;

    }


    public static function getUsers()
    {
       require_once 'CSV.php';
       $csv=new CSV('r',USERS);
       $CSVusers= $csv->getAll();
       $users=array();
       foreach ($CSVusers as $CSVuser){
           $users[]=new User($CSVuser[0],$CSVuser[1],$CSVuser[2],$CSVuser[3],$CSVuser[4],$CSVuser[5],$CSVuser[6]);
       }
       return $users;
    }

    public static function getUserByUsername($username )
    {


       require_once 'CSV.php';
       $csv=new CSV('r',USERS);
       $CSVusers= $csv->getAll();
       $users=array();
       foreach ($CSVusers as $CSVuser){
       $users[]=new User($CSVuser[0],$CSVuser[1],$CSVuser[2],$CSVuser[3]);
       }
        foreach ($users as $user){
            if($user->getUsername()==$username){
                return $user;
            }
        }


    }
}


class CSV
{
    private $handle;
    private $file;

    function __construct($mode,$file) {
        $this->file=$file;
        try {
            $this->handle = fopen($file, "$mode");
        } catch (PDOException $e) {
            exit('Error');
        }
    }

    public function getAll()
    {
        $csv = array();
        //metto tutto il file in un'array
        $lines = file($this->file);

        foreach ($lines as $key => $value)
        {
            $csv[$key] = str_getcsv($value,";");
        }
        fclose($this->handle);
        return $csv;
    }
}

At the moment I get an array from the CSV fole and I transform it into my object in the model but I don't think it is the best solution.





Aucun commentaire:

Enregistrer un commentaire