PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 31, 2022

[FIXED] Cake PHP 2 save data via model in Event Listener

 March 31, 2022     cakephp, cakephp-2.0, cakephp-2.4, php     No comments   

Issue

I've got an event listener in my project's Lib/Event directory and a model called QueueManagerJob.

My application dispatches an event at some point and I'd like to save an entry into my database through my model. When my event is dispatched, it runs a store method in the listener and it's here where I'm referencing my model and am trying to save it.

I've pulled the model in via the $uses array but I'm getting the following error:

Call to a member function set() on null

<?php

App::uses('CakeEventListener', 'Event', 'CakeLog');

class DispatchJobListener implements CakeEventListener {
    public $uses = array('QueueManagerJob');

    public function implementedEvents() {
        return array(
            'QueueManagerModule.QueueManagerJob.dispatchJob' => 'store'
        );
    }

    /**
    * Store the data
    */
    public function store($event) {
        $event->stopPropagation();

        $job = [
            'queue' => 'default',
            'payload' => json_encode([]),
            'attempts' => 0,
            'reserved_at' => null,
            'available_at' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s')
        ];

        $this->QueueManagerJob->set($job);

        // invalid
        if (!$this->QueueManagerJob->validates()) {
            // $this->QueueManagerJob->validationErrors;
            // ...
        }

        // save the job
        $this->QueueManagerJob->save($job);
    }
}

Solution

Your class only implements an interface, there is no further logic that would make use of the $uses property.

The $uses property is only recognized out of the box by controllers, if you need to load models in other places, then you have to use ClassRegistry::init(), like:

App::uses('ClassRegistry', 'Utility');

// ...

$QueueManagerJob = ClassRegistry::init('QueueManagerJob');

Also note that App::uses() only accepts two arguments, the class name and the package name, the third argument in your example won't do anything!



Answered By - ndm
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing