Skip to main content
4 of 10
added 1060 characters in body

Drupal 8 Module layout best practice

I am trying to get to grips with Drupal 8s layout and and architecture.

Having worked with Drupal 6 for the last 2 years I have become used to its procedural style, so I am finding the OOP approach takes a little getting used to.

This is what Im trying to achieve.

My Module has a block which displays content The content of that block is refreshed every 5 seconds This is done with an Ajax call to the server which overwrites the content of the block with the freshly acquired Ajax HTML

So I have gotten the block to display my content on the page easily enough. My problem is now how do I get to the content to refresh. The logic for building the content is contained in functions in my Block class.

I have tried to set up a route in my .yml file to call these functions again to refresh my content via ajax, but I get fatal errors, and also it does not feel like the right approach to access my block class. I feel I should be routing to the controller.

but then, how do I get at the functions that I have written to build the content for the block in the first place?

Should I have written all my logic in my Controller? and if so, how do I access it from my block?

UPDATE

Attempting the solution suggested by Daniel Wehner below I receive the following error:

    Call to undefined method Drupal\livequotes\Controller\LivequotesController::getEntityManager() 
in <b>C:\Work\excel-8\modules\livequotes\lib\Drupal\livequotes\Controller\LivequotesController.php

I guess this is because I need to extend my controller or to implement the class that defines getEntityManager()

any ideas on how to do this?

UPDATE 2

Following on the suggestion in comments from Daniel Wehners answer I have attempted to use dependency injection to give access to EntityManager from my controller.

This is the code for my controller:

    namespace Drupal\livequotes\Controller;

    class LivequotesController{
    
    protected $entity;
    
    public function __construct(EntityManager $em) {
        $this->entity = $em;
    }
    /**
     * Re-render a specific block (yeah if we do something it should be generic).
     */
    public function livequotesShowBlock() 
    {
        $block = $this->entity->getStorage('block')->load($block_id);
        return $this->entity->getViewBuilder('block')->view($block);
    }
}

The following error is received when I try and access function livequotesShowBlock() from my ajax call:

Recoverable fatal error: Argument 1 passed to Drupal\livequotes\Controller\LivequotesController::__construct() must be an instance of Drupal\livequotes\Controller\EntityManager, none given