Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 8 custom module add php classes

Tags:

php

drupal-8

I have created a custom Drupal 8 module that works as is with a custom block and block form to collect some info.

This is all good.

I also have a twig template that I want to render a twitter feed using a php feed class I bought. I just don't know how it integrate this into the module.

This is the setup for the class: http://austinbrunkhorst.com/demos/twitter-class/#setup

It contains two files:

ultimate.twitter.feed.php

and

tmhOAuth.php

Which is currently a require_once 'tmhOAuth.php'; in the head of ultimate.twitter.feed.php

According to the instruction I should be creating a php file that has this:

$options = array(
    'screen_name' => 'FeedTestUser',
    'consumer_key'  => '...',
    'consumer_secret' => '...',
    'user_token' => '...',
    'user_secret' => '...',
);

$twitter = new Twitter($options);

$twitter->PrintFeed();

Which I'm guessing is also a hurdle as twig files are not php

Any help with this is very much appreciated.

C

like image 235
Cybercampbell Avatar asked Oct 18 '22 08:10

Cybercampbell


1 Answers

I would setup the class as a Service in your module. Your block will then implement that service and do the handling. You don't really want to use require_once() if you can avoid it, rather use Drupal constructs (in part so that if you reorganize things later Drupal will help find the files in their new location).

Place the class in your module's src directory, and add a namespace to the start of the file (assuming there isn't one there already). Then in your block's class file you should be able to add a use statement that references that name space (even better would be to use a dependency injection, but the details on that would get in your way here).

In your block class's build() method you then instantiate the class as described in your question, but instead of just letting the module print HTML, you can want to capture that HTML and place it into your block as markup. If the class allows you to do that without using a buffer, you should (but I didn't see anything in the docs to support that), and then attempt to theme the structured data. If not, you can use PHP's output buffering to capture its attempt to print:

 ob_start();
 $twitter->PrintFeed();
 $content= ob_get_contents();
 ob_end_clean();

Then place the generated markup into a render array:

return [ 
  'my_twitter_block' => [
    '#markup' => $content,
  ],
];
like image 179
acrosman Avatar answered Oct 29 '22 01:10

acrosman