1

Apologies if this ends up being a silly syntax oversight.

My services file looks like this:

class MyPluginService extends BaseApplicationComponent {
  public $myArray = array('test1', 'test2');

  public function someFunction() {
    $someText = "This should end up in myArray";
    array_push($this->myArray, $someText);
  }
}

Assuming the "someFunction" has been called, I later try to dump the array.

{{ dump(craft.myPlugin.myArray) }}

Expected output:

array(2) { [0]=> string(5) "test1" 1=> string(5) "test2" [2]=> string(29) "This should end up in myArray" }

Actual output:

array(2) { [0]=> string(5) "test1" 1=> string(5) "test2" }

The solution seems to be pretty unanimous across many PHP related forums. However, this just isn't working in my Craft project. Have I overlooked something obvious, or is Craft protecting the public array in some way?

2

I feel like we're missing some code in your examples, but in a plugin there is no direct link between a template and its services. You go through a Variable class, which is responsible for exposing your service's methods.

So in your example, in your plugin's variables folder, you'd have a MyPluginVariable class that has it's own someFunction method like this:

class MyPluginVariable
{
    public function getMyArray()
    {
        return craft()->myPlugin->myArray;
    }

    public function someFunction()
    {
        return craft()->myPlugin->someFunction();
    }
}

Then from your template, assuming you call someFunction() first, you should get the correct output.

{{ craft.myPlugin.someFunction() }}
{{ dump(craft.myPlugin.myArray }}

I'd also recommend refactoring your service to encapsulate the public array in a method and use the PHP [] syntax to avoid the function overhead of array_push().

Something like this:

class MyPluginService extends BaseApplicationComponent
{
    private $_myArray = array('test1', 'test2');

    public function someFunction()
    {
        $someText = "This should end up in myArray";
        $this->_myArray[] = $someText;
    }

    public function getMyArray()
    {
        return $this->_myArray;
    }
}

Then your Variable's getMyArray() method would change to this:

public function getMyArray()
{
    return craft()->myPlugin->getMyArray();
}
2
  • Thank you Brad (and apologies for the late response). Not only did you elaborate on my own question, but you've answered it perfectly. Extrapolating from you answer, most of my issues are down the syntaxing issues. I think you need to get one of those "buy me a beer" buttons next to your name... you've helped me out various times now. Thanks again. – Mark Notton Nov 8 '15 at 1:06
  • Hah... next time I'm in the UK, I'll take you up on the beer! – Brad Bell Nov 8 '15 at 7: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.