StuBlackett
StuBlackett

Reputation: 3857

Variables in Trait

I have created a trait in Laravel.

In myconstruct I am calling a setting('value') - This is provided by the qcod/laravel-app-settings package.

But inside my methods when I reference $this->token or $this->org_id it returns NULL

I know the values are set, as they're showing in the config and are also set correctly in the Database.

My PHP code is :

<?php

namespace App\Traits;

use Illuminate\Support\Facades\Log;

trait PropertyBaseTrait
{

    private $org_id;
    private $token;
    private $is_set;

    public function __construct()
    {
        $this->org_id = setting('propertybase_org');
        $this->token = setting('propertybase_token');
    }

    public function base_url($method)
    {
        return 'https://pb-integrations-api-staging.herokuapp.com/api/v1/'.$method.'/'.$this->org_id.'';
    }

    public function post_lead($data)
    {
        $lead_data = array(
            'first_name'        => '',
            'last_name'         => '',
            'email'             => '',
            'phone1'            => '',
            'phone2'            => '',
            'phone3'            => '',
            'address'           => '',
            'city'              => '',
            'state'             => '',
            'zip_code'          => '',
            'country_name'      => '',
            'landing_page'      => '',
            'search_term'       => '',
            'referral_source'   => ''
        );

        $object_type = 'lead';
        $action_type = 'create';

        dd($this->token);

        $endpoint = $this->base_url('messages');

        $this->post_data( $endpoint, $object_type, $action_type, json_encode($data));
    }

Upvotes: 2

Views: 2257

Answers (2)

Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

The problem is that you have construct in your trait and maybe in your class where you are using this trait. possible scenario:

class MyClass {
    use MyTraitWithConstructor;

    public function __construct(){
        ...
    }
}

In this case trait constructor doesn't work.

What You can do?

You can rename trait construcor like this:

class MyClass {

    use PropertyBaseTrait {
        PropertyBaseTrait::__construct as private __prConstruct;
    }

    public function __construct(){
        $this->__prConstruct();
        ...
    }
}

Upvotes: 3

nmfzone
nmfzone

Reputation: 2903

Avoid writing constructor in traits. That's what I can say.

Instead, you can make them as normal method, then just call it in your class constructor.

Trait

trait Bar
{
    public function init()
    {
        $this->org_id = setting('propertybase_org');
        $this->token = setting('propertybase_token');
    }
}

Class

class Foo
{
    use Bar;

    public function __construct()
    {
        $this->init();
    }
}

Upvotes: 2

Related Questions