Reputation: 33435
I have some PHP code which looks roughly like this
require_once 'cache.php';
require_once 'generator.php';
if (cache_dirty ('foo')) {
cache_update ('foo', generate_foo ());
}
print cache_read ('foo');
My problem is that generator.php
includes a whole mass of libraries and I don't want to load/parse it unless cache_dirty
actually returns false
at runtime.
I know there are PHP precompilers which can help but for now I need a quick fix. Is this possible?
Upvotes: 4
Views: 2592
Reputation: 449783
As PeeHaa already said in his comment, Autoloading is usually the ideal way to go (although it will require restructuring your app.)
However, in the situation you show, I'm not sure what's keeping you from doing
require_once 'cache.php';
if (cache_dirty ('foo')) {
require_once 'generator.php';
cache_update ('foo', generate_foo ());
}
?
Upvotes: 5
Reputation: 1224
If your code is OO (object oriented), you should be using PHP's __autoload()
feature.
Otherwise, just use conditional require_once()
s.
Upvotes: 1
Reputation: 26837
Just include / require generator.php
in the if
block. Also, you shouldn't have a space between your function names and (
in function calls.
Upvotes: 1
Reputation: 65332
require_once 'cache.php';
if (cache_dirty ('foo')) {
require_once 'generator.php';
cache_update ('foo', generate_foo ());
}
print cache_read ('foo');
Fits your question quite well ...
Upvotes: 6
Reputation: 98559
You should write a PHP __autoload
function to dynamically require generator.php
when a generate_foo
call is found.
Upvotes: 2