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

Consider implementing interfaces? #14

Open
dingo-d opened this issue Mar 11, 2021 · 0 comments
Open

Consider implementing interfaces? #14

dingo-d opened this issue Mar 11, 2021 · 0 comments

Comments

@dingo-d
Copy link

dingo-d commented Mar 11, 2021

Hi!

So far I'm really liking the lib, haven't tested it fully just yet, but I'll do that really soon.

I've noticed one thing while trying to build a factory for my background jobs. Because I really try to avoid instantiating classes inside my classes and prefer to use dependency injection, I had to create a static factory to generate my job.

My job is being run by ajax callback, which I have added as a class with its own handler. So first I tried to just add the job as a dependency, but my job has multiple dependencies, so that was a no-go.

So I did something like this:

<?php

/**
 * File holding jobs factory class
 *
 * @package MyProject\BackgroundJobs
 */

declare(strict_types=1);

namespace MyProject\BackgroundJobs;

use WP_Queue\Job;

/**
 * Class JobFactory
 *
 * Creates a background job with all the dependencies.
 */
final class JobFactory
{
	/**
	 * Create and return an instance of the background job.
	 *
	 * Couldn't specify the interface as the return type
	 * because of the push() method which typehints against a specific class (Job).
	 *
	 * @param string $jobName Name of the job to execute.
	 * @param mixed ...$args Job arguments. Can be one or many.
	 *
	 * @return Job Specific WP_Query job.
	 */
	public static function createJob(string $jobName, ...$args): Job
	{
		return new $jobName(...$args);
	}
}

and now I can call this in my ajax callback

wp_queue()->push(JobFactory::createJob(MyCustomJobJob::class, $dependency1, $dependency2, $dependency3), 10);

Which works fine. But it's still tightly coupled to a Job class (return value of my factory creator) because the push method expects a Job class as a first parameter. If that was not the case, I'd just typehint against my own JobHandlerInterface. This would give me more leeway down the road if, for whatever reason, I'd change the bg jobs library.

So what can be done to do that? Just add your own interface for the Job template class. That way my interface can extend that interface, and even if the implementation changes down the road, I can just remove the extension, but the factory should work because I'd typehint against my own interface.

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

No branches or pull requests

1 participant