Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new() Twig function to create PHP objects #3921

Closed
wants to merge 1 commit into from

Conversation

khalwat
Copy link
Contributor

@khalwat khalwat commented Feb 27, 2019

Craft has already added the clone() function, and exposed all of craft.app in Twig templates. One missing piece of the puzzle is the ability to create new PHP objects via Twig.

Many plugins exist just to expose this functionality, and this would eliminate the need. For example, a recent discussion came up as whether to use my Cookies plugin or use functionality already exposed by Craft.

From the Yii2 docs:

Yii represents each cookie as an object of yii\web\Cookie. Both yii\web\Request and yii\web\Response maintain a collection of cookies via the property named cookies. The cookie collection in the former represents the cookies submitted in a request, while the cookie collection in the latter represents the cookies that are to be sent to the user.

We can get most of the way there via:

{%  set requestCookies = craft.app.request.cookies %}
{%  set responseCookies = craft.app.response.cookies %}

...which will give us a CookieCollection that we can use to access or remove cookies... but we can't add new cookies, because ::add() needs a yii\web\Cookie object passed to it.

This is just one example where a plugin could be eliminated, and the core functionality of Craft used to accomplish some common things.

@brandonkelly
Copy link
Member

Let’s call it create() instead of new(), and point it at Craft::createObject() rather than an inline function in the Twig extension class.

That way it won’t only work for classes with $config as the first constructor argument, and you’ll get a couple different supported syntaxes.

{% set obj = create('my\\class\\name') %}

{% set obj = create({
    class: 'my\\class\\name',
    configOpt1: 'foo',
    configOpt2: 'bar'
}) %}

{% set obj = create('my\\class\\name', [
    'constructArg1',
    'constructArg2'
]) %}

@khalwat
Copy link
Contributor Author

khalwat commented Feb 27, 2019

Works for me. You want to do it, or should I?

@brandonkelly
Copy link
Member

I’m on it…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants