Domanda

I have seen some similar questions but I have yet to find a good solution for this from the interface all the way to the controller.

My Problem:

I have a few different kinds of applications that will require restarts, each has its own logic for restarting the application(SSH,API calls, etc.). I have set up an interface because although different logic, they all will need some similar functions. I have also created 3 classes, one for each app that implements that interface. where I am having issues is understanding the best way to keep the logic as abstracted from the controller as possible.

Some Questions:

Should I also be creating an Abstract class? Should this be one controller that handles all types and chooses the correct one? do I simply inject the different classes into the controller?

Code:

RestartInterface.php

<?php  namespace Application\Service\Restart;

   interface RestartInterface {

       public function start();

       public function stop();

       public function restart();
   }

example of implementing class:

<?php namespace Application\Service\Restart\AppOne;

   use Application\Service\Restart\RestartInterface;

    class AppOneRestart implements RestartInterface {

       public function start() {

       }

       public function stop() {

       }

       public function restart() {

       } 

   }

How could I use a service provider to keep this as modular as possible? What is the best practice in this situation, I would like to be able to use many or as little restart implementations as I want.

thanks!

È stato utile?

Soluzione

An abstract class is a way to create a base class you don't need your developers instantiating directly because, usually, there is still missing code from it, like, methods were not fully implemented. So you create an abstract which implements the common methods of your concrete restart classes

abstract class Restart {

   public function restart() {

   } 

}

And then you implement one by one of those classes extending your abstract and creating the missing methods:

class AppOneRestart extends Restart implements RestartInterface {

   public function start() {

   }

   public function stop() {

   }

}

Option 1

If your whole application can use a single implementation of it and you just need the ability to swap from one to another, because your business somehow changed, a simple binding will do the trick:

App::bind('RestartInterface', 'AppOneRestart');

Option 2

If during a request you might need one or another, you probably will need to implement the Factory pattern: http://en.wikipedia.org/wiki/Factory_method_pattern, so you inject the factory in your controller:

class RestartApiController extends Controller {

    public function __construct(RestartFactory $factory)
    {
        $this->restart = $factory->make('api');
    }

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top