I wouldn't use a controller to be used as a service layer, as it couples to different interfaces to each other. There are two ways you can solve this. First is to make a client-side frontend using your RESTful interface, another is offloading controller logic to reusable services.
If you go with the first option, you "just" have a RESTful controller and no "human" controller. Your api uses the REST interface and for the html version you use something like angular.js, backbone.js or ember.js. These tools work well with REST api backends to load pages and it saves you development time on the backend as you need to write your controllers once.
A second option is to offload most of the logic to service layers. This helps to make your controllers slim. This is the method I use mostly. I have a subnamespace "Api" and "Web" (as MyModule\Controller\Api\FooController) and there are totally decoupled. The routing is different and the interface is different. The RESTful controllers apply the REST parameters with methods like get(), getList() and create(), the web controllers are 1:1 mapped to pages (viewAction(), editAction() and so on).
Both use the same services, so the code reuse is maximised. An example of such service for a blog post controller is this (using Doctrine):
<?php
namespace Blog\Service;
use Doctrine\Common\Persistence\ObjectManager;
use Blog\Entity\Post as PostEntity;
class Post
{
protected $objectManager;
protected $objectRepository;
public function __construct(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
$this->objectRepository = $objectManager->getRepository('Blog\Entity\Post');
}
public function find($id)
{
return $this->objectRepository->find($id);
}
public function store(array $data)
{
$post = new PostEntity;
$post->fromArray($data);
$objectManager = $this->objectManager;
$objectManager->persist($post);
$objectManager->flush();
}
public function update(array $data, PostEntity $post)
{
//
}
public function delete(PostEntity $post)
{
//
}
}
These kind of services can both be used for your "human" controllers and your RESTful controllers. Yes, you might have a little bit of code duplication, but with services you mostly remove this duplication. If you have left some duplicated code, you always have to consider:
- A slight amount of code duplication isn't worrisome if it decouples both objects
- Code used in multiple places serving a common goal can be abstracted into a controller plugin