Custom component error

Hi guys,

I'm trying to use phalcon component but it gives me an error


Fatal error: Call to undefined method HomeController::randomize() in C:\Users\spilagan20140973\Desktop\xammp1\htdocs\PHALCON\app\controllers\HomeController.php on line 54

here is my code

library folder has a AppRandomize.php

<?php
use Phalcon\Mvc\User\Component;

class AppRandomize extends Component{
    public function initialize(){

        return str_shuffle($string);
    }
}

config.php


define('CONF_DIR', __DIR__."/../../app/");

'application'   => [
        'libraryDir'        => CONF_DIR . 'library/'
    ],

loader.php


$loader->registerDirs([
        $config->application->libraryDir
    ])->register();

services.php


$di->set('randomize', function(){

    return new AppRandomize();
});

HomeController.php


<?php
class HomeController extends BaseController{

  public $string;

  public function initialize(){

  self::$string = "steventestrandom";
  $rand = $this->randomize(self::$string);

  echo $rand;
  }
}

Problem is that $this->randomize() is a function call on HomeController.

I think what you need is something like this:

<?php
use Phalcon\Mvc\User\Component;

class AppRandomizer extends Component{
    public function randomize($string){

        return str_shuffle($string);
    }
}
$di->set('randomizer', function(){

    return new AppRandomizer();
});

Maybe you should use setShared() for registering service to use singleton pattern.

<?php
class HomeController extends BaseController{

  public $string;

  public function initialize(){

  self::$string = "steventestrandom";
  $rand = $this->randomizer->randomize(self::$string);

  echo $rand;
  }
}

I haven't tested this but it should work.