0

I'm trying to create some logic in order to have my code better organized, so I am creating a module and trying to separate functions in different files according to it's content type.

For example, I have a module called my_module and I'm creating two content_types content_type1 and content_type2

So I created this structure:

  • my_module.install
  • my_module.module
  • my_module.content_type1.inc
  • my_module.content_type2.inc

This logic inside install:

function my_module_install() {
  // During installation, the t() function is unavailable, so we use get_t()
  // to store the name of the translation function.
  $t = get_t();

  //List of objects to be created
  $nodes = array('content_type1','content_type2');

  //Create all the content-types from the array
  foreach ($nodes as &$node_name) {
    error_log('Create: '.$node_name, 0);
    call_user_func('_'.$node_name.'_create_node',$node_name);
  }

  unset($node_name);   
}

And this logic inside each file ( content_types )

function _content_type1_create_node($node_name='type1') {}

function _content_type2_create_node($node_name='type2') {}

Since I added this lines to the my_module.info:

files[] = my_module.content_type1.inc
files[] = my_module.content_type2.inc

I was expecting to have all the logic working as it should but

//content_type1_create_node()
call_user_func('_' . $node_name . '_create_node', $node_name);

It cannot find the callback and I think it's because the callback.

Am I over engineering, or doing it wrong?

2

Your functions are in files that haven't yet been included, try changing your code to this:

foreach ($nodes as &$node_name) {
  module_load_include('inc', 'my_module', 'my_module.' . $node_name);

  $func = '_'.$node_name.'_create_node';
  if (function_exists($func)) {
    call_user_func($func, $node_name);
  }
}

I've never been able to get the files[] key in the .info file to work, I don't think it's used for arbitrary files but rather those that will form part of Drupal's code registry (using hook_hook_info() or something like that), but I haven't delved too deeply so it's worth checking yourself.

To answer your final question, yes I think you're over-engineering this a bit :)

It would make sense to do this if your module is going to become generic (so more content types can be catered for) but if it's really just 2 content types I'd put the code inside the .module file to be honest.

Obviously if you think these files will end up having a lot of code it makes sense to separate them, but if not I don't think you're really getting much benefit for doing so.

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.