Question

I have a question that keeps bothering me. Currently, I have started using Kohana 3.2 Framework. I've written a helper to handle some functionality - I have a number of methods, which are (as it should be) declared STATIC. But, all of these methods are somehow working with the database, so I need to load a model. Currently, every method has a non-static variable like this:

$comment = new Model_Comments;
$comment->addComment("abc");

OK, it seems to be working, but then I wanted to get rid of this redundancy by using class attribute to hold the instance of the model (with is class as well).

Something like this:

private static $comment; // Declaring attribute
self::$comment = new Model_Comment; // This is done within helper __constuct method
self::$comment->addComment("abc"); // And call it within the method.

But, I got failed with: Call to a member function addComment() on a non-object

Question is: is it possible to do it ? Maybe there are some other approaches ?

Sorry for a long story and, thanks in advice! :P

Was it helpful?

Solution

A static method cannot call a non-static method without operating on an instance of the class. So, what you're proposing won't work. There may be a way do accomplish something similar, but what about trying the following:

You could implement the singleton or factory pattern for your "helper" class. Then, you could create the model (as an attribute) as you instantiate/return the instance. With an actual instance of your "helper" class, you won't have to worry about the static scope issues.

In other words, you can create a helper-like class as a "normal" class in your application that, upon creation, always has the necessary model available. I'd be happy to help further if this approach makes sense.

David

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top