1

I'm creating a custom module which uses a few hooks and then after the form is submitted it will dive into custom PHP interaction that interfaces with an external restful API.

I want some of these variables and functions to be private as they will contain business rules and some variables that I wouldn't want someone to get their hands on (easily).

I'm uncertain of how to do this in Drupal. I understand that I would need to create a PHP class which would then have private/public methods available inside of it. But how do I do this?

Do I build this PHP class in its own file outside of my .module file and then use files[] = includes/MyClass.class.php in my .info file to import this external class file in?

Then once it's successfully imported in I could instantiate it with $something = new MyClass();?

Is it that simple to do, or is there another/better way?

2

Yes - it's that simple. Remember; Drupal is only PHP.

Although your class should be called MyClass.php rather than MyClass.class.php to adhere to the Drupal Coding Standards for OO code (note - this isn't explicitly declared, but is hinted at when they describe the Interface file naming conventions).

Just to pad this out a bit; you could also use the X Autoload module to allow for PSR-4 style autoloading instead of adding your class in the files[] array. I do this for as much D7 code as possible now (where I'm not using Composer Manager), and would whole heartedly recommend it.

xautoload is a comprehensive and yet highly efficient PHP class loading suite.

Most importantly, it provides Drupal-8-style PSR-4 (and the old D8 PSR-0-style in "lib") autoloading for Drupal 7. But it is also a great tool for 3rd party autoloading.

  • Good catch! So how exactly does X Autoload work if I were to install it? @Chapabu – Exziled Jan 10 '16 at 2:30
  • That isn't a discussion for comments or as an addendum to a different question @Exziled - if you have specific questions about xautoload after you've read the module page/documentation and installed/used it, please ask them as separate questions – Clive Jan 10 '16 at 10:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.