Drupal - "Drupal calls should be avoided in classes, use dependency injection instead"
Take the BlockLibraryController
class as example; it extends the same class as your controller.
You define:
- A static and public
create()
method that gets the values from the dependency container, and creates a new object of your class - A class constructor that saves the values passed from the previous method in object properties
- A set of object properties to save the values passed in the class constructor
In your case, the code would be similar to the following one.
class MyModuleController extends ControllerBase {
/**
* The path alias manager.
*
* @var \Drupal\Core\Path\AliasManagerInterface
*/
protected aliasManager;
/**
* Constructs a MyModuleController object.
*
* @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
* The path alias manager.
*/
public function __construct(AliasManagerInterface $alias_manager) {
$this->aliasManager = $alias_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('path.alias_manager')
);
}
/**
* {@inheritdoc}
*/
public function getUserContent() {
$alias = $this->aliasManager->getPathByAlias($_POST['url']);
// Omissis.
}
}
Don't forget to put use \Drupal\Core\Path\AliasManagerInterface;
on the top of the file containing the code you are showing.
As side note, the code you use to render the view is wrong: You don't need to use drupal_render()
because views_embed_view()
already returns a renderable array.
Then, the render array you are returning is probably not giving the output you expect. #name is probably not going to be used from Drupal, and #markup filters the markup you are passing to it, as described on Render API overview.
#markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through
\Drupal\Component\Utility\Xss::filterAdmin()
, which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e,<script>
and<style>
are not allowed.) See\Drupal\Component\Utility\Xss::$adminTags
for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed_tags to alter which tags are filtered.#allowed_tags: If #markup is supplied this can be used to change which tags are using to filter the markup. The value should be an array of tags that
Xss::filter()
would accept. If #plain_text is set this value is ignored.