Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [PHP] Uniwersalne tworzenie obiektów klas o nazwach ze string'a
eerie
post
Post #1





Grupa: Zarejestrowani
Postów: 114
Pomógł: 0
Dołączył: 3.08.2017

Ostrzeżenie: (0%)
-----


Sorry, jeśli odpowiedź na moje pytanie jest banalna. Jednak szukam w Google i nie mogę nic znaleźć.

Chcę przekazywać parametrem metody stringi (np. 'NewClass'), na podstawie których będę tworzyć obiekty (np. $object = new NewClassModel()). Potem chcę te obiekty zwracać (return $object). Chodzi o to, aby to było uniwersalne. Jak to prosto zrobić?
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
eerie
post
Post #2





Grupa: Zarejestrowani
Postów: 114
Pomógł: 0
Dołączył: 3.08.2017

Ostrzeżenie: (0%)
-----


Ok. Nikt nie odpowiedział na moje pytanie odnośnie interfejsów w oddzielnym temacie, więc zrobiłem to na czuja. PHP nie wywala błędów i niby wszystko działa ok, ale nie jestem pewny, czy jest to napisane fachowo...

Kod
<?php

declare(strict_types=1);

namespace App\Repository;

use App\Contract\{ModelInterface, RepositoryInterface};

class TestRepository implements RepositoryInterface
{
    protected ModelInterface $model;

    public function __construct(ModelInterface $model)
    {
        $this->model = $model;
    }

    // [...]
}


Kod
<?php

declare(strict_types=1);

namespace App\Core;

use App\Contract\ModelInterface;
use App\Core\Model;

class Controller
{
    protected Model $model;

    public function getModelManager(): ModelInterface
    {
        if (!isset($this->model)) {
            $this->model = new Model();
            $this->model->dbConnect();
        }

        return $this->model;
    }
}


Kod
<?php

declare(strict_types=1);

namespace App\Core;

use App\Contract\{ModelInterface, RepositoryInterface};
use App\Core\DataBase;

class Model extends DataBase implements ModelInterface
{
    protected array $repository;

    public function getRepository(string $name): RepositoryInterface
    {
        $class = 'App\\Repository\\' . $name . 'Repository';
        $this->repository[$name] (IMG:style_emoticons/default/questionmark.gif) = new $class($this);

        return $this->repository[$name];
    }
}


Kod
<?php

declare(strict_types=1);

namespace App\Contract;

use App\Contract\ModelInterface;

interface RepositoryInterface
{
    public function __construct(ModelInterface $model);
}


Kod
<?php

declare(strict_types=1);

namespace App\Contract;

use App\Contract\RepositoryInterface;

interface ModelInterface
{
    public function getRepository(string $name): RepositoryInterface;
}
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 3.10.2025 - 05:12