statamic / v2-hub

Statamic 2 - Feature Requests and Bug Reports
https://statamic.com
95 stars 5 forks source link

Private Variables on ContentCollection #1833

Open jnbn opened 6 years ago

jnbn commented 6 years ago

I was creating an addon by using an Eloquent Model but decided to extend it from CollectionTags class to make it easier to use parameters, pagination etc. (for easier output)

But realized that all variables on CollectionTags are private so that they can not be used on any extended class.

After changing them to protected you can use any models or items as tags by just typing 3 lines of code like:

<?php

namespace Statamic\Addons\Questions;

use Statamic\Extend\Tags;
use Statamic\Addons\Collection\CollectionTags;

use Statamic\Addons\Questions\Models\Question;

class QuestionsTags extends CollectionTags
{

    public function index()
    {
        $this->collection = Question::where("is_published",1)->with('answers')->orderBy ("id","DESC")->get();

        $this->limit();

        return $this->output();

    }

}

So briefly I suggest changing private variables on CollectionTags to protected variables.

jnbn commented 6 years ago

Working code on .html template is like:

{{ questions limit="10" paginate="true" }}
  {{entries}}
   . ...
   {{ answers }}
        ....
   {{ /answers }}
   {{ /entries }}
   {{ partial:pagination }}
{{ /questions }}
jasonvarga commented 6 years ago

What in your code example is private? Where are you using ContentCollection?

jnbn commented 6 years ago

I think I mistyped it.

Private variables are on Statamic\Addons\Collection\CollectionTags (not on ContentCollection)

image

jasonvarga commented 6 years ago

Right, but which ones are you trying to use?

jnbn commented 6 years ago

I just tried to use pagination parameter with limit (as always) {{ questions limit="10" paginate="true" }}

But all variables on CollectionTags are connected to each other (set from the related method) and as they're protected I think I can not access them on extended class. (QuestionTags)

On the other scenario I had to extend QuestionTags from Statamic\Extend\Tags and copy/paste all stuff for pagination, limit, offset with their methods.

jnbn commented 6 years ago

would you like me to describe it from the scratch @jasonvarga ?

jackmcdade commented 6 years ago

Please do!

jnbn commented 6 years ago

We were in need of a custom tag for our Questions named QuestionTag that works with an Eloquent model Question.

So I started digging out.

While I was trying I realized that all necessary functions and methods were similar to what we need. So I extended it from Statamic\Addons\Collection\CollectionTags.

But as methods were in need of using privately defined variables on CollectionTags we had some problems. And I suggested you to change them to protected instead of private.

After changing them to protected we could extend and use it only by overriding index function on QuestionTags.