Facade Pattern, is this ok? - facade

I have two servers that I will be connecting to from one client. For each server, I will be doing an ftp "put" and a "rm".
Should I build one facade, and have an interface like this:
void putFileOnServer1(String file)
void putFileOnServer2(String file)
void removeFromServer1(String file)
void removeFromServer2(String file)
And, should the facade handle all the establishing of the connections and disconnecting?
If so, should it use a factory to do so?

You have two methods, PutFileOnServer and RemoveFromServer. Which server you are putting or removing from should be part of the abstraction.

Do the ftp servers have different interfaces? Or do they all understand the same set of commands you want to utilize already?
If so, then simply create one FtpServer class that accepts connection info. And create a FtpClient class that accepts multiple servers, that you can select by some key for instance. (At least this, to some extent, would probably be something I would do).
class FtpClient
{
public function addServer( FtpServer $server, $key );
public function selectServer( $key );
public function putFileOnServer( $file );
public function removeFileFromServer( $file );
}
If not, and you have a class for each individual implementation already, that differ by their interfaces, for instance like:
class FtpServerFoo
{
public function selectFile( $file );
public function removeSelectedFile();
}
class FtpServerBar
{
public function removeFile( $file );
}
... you should look into the Adapter Pattern:
abstract class FtpServer
{
abstract public function putFile( $file );
abstract public function removeFile( $file );
}
class FtpServerAdapterFoo
extends FtpServer
{
public function __construct( FtpServerFoo $server )
{
}
public function removeFile( $file )
{
$this->server->selectFile( $file );
$this->server->removeSelectedFile();
}
}
class FtpServerAdapterBar
extends FtpServer
{
public function __construct( FtpServerBar $server )
{
}
public function removeFile( $file )
{
$this->server->removeFile( $file );
}
}
$cilent = new FtpClient();
$client->addServer( new FtpServerAdapterFoo( new FtpServerFoo() ), 0 );
$client->addServer( new FtpServerAdapterBar( new FtpServerBar() ), 1 );
$client->selectServer( 0 );
$client->putFileOnServer( $file );
$client->selectServer( 1 );
$client->removeFileFromServer( $someOtherfile );
If you don't have individual classes for differing FTP servers yet, then you can just implement the same interface (or inherit an abstract class) for each ftp server implementation and use the same type of FtpClient class as the one above again.
Not really a facade pattern involved here though.

You typically use facades to decrease complexity among multiple object types. In this case, though, it appears you want to use only one functional "type", a "FTPServer". For the most part, then, you should just have two instances of this type, and this type will have a "put" and "remove" method.
When you add needless function points, you actually increase the complexity of maintenance. For instance, if you need to add a new parameter to your functions (maybe access restrictions or whatever), you not only have to change for each place of use, but now have to add in each facade method. Abstraction should reduce this type of coupling, not increase it.

Related

the difference when using the initialization function in php

I'm not understanding how to use the initialization function in the code below. Can you explain it to me?
Class A
{
protected $classB;
public function __construct()
{
$this->classB = new ClassB();
}
}
Class A
{
protected $classB;
public function __construct(ClassB $classB)
{
$this->classB = $classB;
}
}
in the second way you always have to make your object like this.
$clasa = new ClassA($classb);
in the first way you are creating the object inside of the constructor.
the second way is an injection. and could be usefull when for example you need some attributes already seted in the object.

How to set listener queue name from environment variable?

I just noticed that some of my listeners do not use the queue I expected them to use. Our team upgraded from Laravel 5.2 to 5.5 a few weeks back, and I guess this is when the problem started happening. There hasn't been much load on the system, so I only discovered it by accident.
Anyway. I used to set the queue name on the listener through a queue method, like so:
public function queue(QueueManager $handler, $method, $arguments): void
{
$handler->connection()->push($method, $arguments, Queue::getNotificationQueue());
}
This approach is not working anymore, so a default queue ends up handling the job instead of the expected notification queue.
So I looked at the documentation https://laravel.com/docs/5.5/events#queued-event-listeners, which states that the name should be set on a queue property on the listener. My problem is that I have the queue name in an environment variable, so I cannot just set it directly as a property, as shown in the documentation and it does not work to set it on the constructor, like so:
protected $queue;
public function __construct()
{
$this->queue = Queue::getNotificationQueue();
}
Does anyone here have an idea of how I can get around this?
Specifically for SQS queues the $queue property acts a bit weird because it doesn't seem to refer to queues defined in queue.php, but it expects a full queue url, so even the example in the documentation seems off.
But for dynamic queue names on queued event listeners that for example changes depending on environment, making a custom SqsConnector and SqsQueue will be one way to solve your issue.
Here is an example of implementation.
ACMEEventListener.php
class ACMEEventListener implements ShouldQueue
{
public function handle(Event $event): void
{
// I'm going to a custom queue
}
public static function getQueue(): string
{
return 'https://sqs.eu-central-1.amazonaws.com/<account id>/<queue name>';
}
}
CustomSqsConnector.php
use Illuminate\Queue\Connectors\SqsConnector;
use Aws\Sqs\SqsClient;
class CustomSqsConnector extends SqsConnector
{
public function connect(array $config)
{
$sqs = new SqsClient($config);
return new CustomSqsQueue($sqs, $config['queue']);
}
}
CustomSqsQueue.php
class CustomSqsQueue extends \Illuminate\Queue\SqsQueue
{
public function push($job, $data = '', $queue = null)
{
if ($job instanceof CallQueuedListener && method_exists($job->class, 'getQueue')) {
$queue = $job->class::getQueue();
}
return $this->pushRaw($this->createPayload($job, $data), $queue);
}
}
CustomSqsQueueServiceProvider.php
class CustomSqsQueueServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->booted(function () {
$this->app['queue']->extend('custom_sqs', function () {
return new CustomSqsConnector;
});
});
}
}
And then in your queue.php, your default SQS connection driver from sqs to custom_sqs

Laravel model properties

I'm not sure how to best ask the question. I'm trying to write DRY code and I've got a Job model. A job can have types (ex: full-time, part-time, etc). If I want to only define the types once where would I put them that I could use them everywhere? Is the best way to do this something like:
class Job extends Model
{
private static $jobTypes = [
'full-time',
'part-time',
];
public static function jobTypes()
{
return self::$jobTypes;
}
}
Or does doing a completely separate class make more sense / increase flexibility?
class JobTypes
{
private static $jobTypes = [
'full-time',
'part-time',
];
public static function jobTypes()
{
return self::$jobTypes;
}
}
Or something else...
Based on the requirement, your first response would be the best practice:
class Job extends Model
{
private static $jobTypes = [
'full-time',
'part-time',
];
public static function jobTypes()
{
return self::$jobTypes;
}
}
However, sometimes it's beneficial to have all of these variables defined at one place so that you can modify them easily. So if you have more static options like this for various models or for whatever reason, I would suggest to go with config file and define them in: config->app.php
and then you can access them from anywhere like so:
config('app.jobTypes')
Makes sense?

How can I filter fields before they reach Input::get("my_field")?

I want for example to remove the word "fck" of all input fields. I know I can do it after but it would be great if I can do it before so it applies to my entire app.
In other words, where do I have to modify the Input (or http or request) class of Laravel 4?
Well, there are a few possibilities. The easiest and simplest one is to simply make a new Input facade and override its get method. Something like this:
app/extensions/FilterableInput.php
use Illuminate\Support\Facades\Input as IlluminateInput;
class FilterableInput extends IlluminateInput {
public static function get($key = null, $default = null)
{
return static::filterInput(parent::get($key, $default));
}
// Filtering method
protected static function filterInput($value)
{
if (is_string($value))
{
return str_replace('fck', '***', $value);
}
return $value;
}
}
Don't forget to replace the Input alias on app/config/app.php with FilterableInput and to add app/extensions to your composer.json autoload.classmap settings.

Problems writing C# method parameter validation that supports fluent interface (call chaining)

I'm trying to write a generic method parameter validation functionality that can be chained (fluent interface) to attach more and more validations/checks like:
public void SomeMethod(User user, string description)
{
ParameterHelper
.Create(() => user)
.RejectNull();
ParameterHelper
.Create(() => description)
.RejectNull()
.RejectEmptyString();
// now this would be luxurious
ParameterHelper
.Create(() => new { user = user, desc = description })
.RejectNull(o => o.user)
.RejectNull(o => o.desc)
.RejectEmptyString(o => o.desc);
}
I would like to use this helper class to test method parameters for certain values before using them (most of the time null will be tested).
Current state of affairs
I first started writing static helper class without the Create() method like:
public static class ParameterHelper
{
public static void RejectNull(Expression<Func<T>> expr)
{
if (expr.Compile()().Equals(default(T)))
{
MemberExpression param = (MemberExpression)expr.Body;
throw new ArgumentNullException(param.Member.Name);
}
}
}
But this doesn't allow chaining. That's why I created the Create() method that would return something that can be used by chained extension methods.
The problem
I would like to avoid multiple Compile() calls, so basically my Create() method should return Func<T> and reject methods should be extension methods of Func<T>.
If my Create() does return Func<T> I don't get the chance to read parameter names that should be supplied to various exceptions (using MemberExpression).
If I return Expression<Func<T>> instead I will have to call Compile() in each Reject extension method.
Questions
Is there a C# library that already does this kind of chaining?
If not, what do you suggest how this should be done? Any examples from the web would be warmly welcome.
Additional note
I should point out that complex/long validation invocation code is not an option here, because my current validation is done like:
if (user == null)
{
throw new ArgumentNullException("user");
}
or
if (string.IsNullOrEmpty(description))
{
throw new ArgumentNullException("description");
}
Which has two major drawbacks:
I repeat the same lines of code over and over
it uses magic strings
So validation should be done with a one liner per check as described above in the desired scenario.
There is a simple way to implement such a fluent interface. Your 'ParameterHelper.Create' method should return an instance of some class (this class is named Requirements below). This instance should hold the expression which was passed to Create. Also this class should have Require... instance methods which will validate expression and return this. Requirements class can be a private class inside ParameterHelper. I would also introduce an interface for this requirements chain (this interface is named IRequirements below. Sample:
public static class ParameterHelper
{
public static IRequirements Create<T>(Expression<Func<T>> expression)
{
return new Requirements{ Expression = expression };
}
private class Requirements<T> : IRequirements
{
public readonly Expression<Func<T>> Expression { get; set; }
public IRequirements RejectNull()
{
if (Expression .Compile()().Equals(default(T)))
{
MemberExpression param = (MemberExpression)Expression.Body;
throw new ArgumentNullException(param.Member.Name);
}
return this;
}
// other Require... methods implemented in the same way
}
}
public interface IRequirements
{
IRequirements RejectNull();
}
This approach will allow you implementing your luxurious solution - you just need to add a corresponding parameters to Reject... methods. Also you will probably need to make IRequirements interface generic.
Robert,
I have a library that solves this problem. It is called Bytes2you.Validation (Project). It is fast, extensible, intuitive and easy-to-use C# library providing fluent APIs for argument validation.
It focuses exactly on the problem that you want to solve, but does not use expressions. This is so, because they are a lot slower than just passing the argument name. For a library like that, that is designed to be used everywhere the performance is one of the most critical features.
For example:
Guard.WhenArgument(stringArgument,"stringArgument").IsNullOrEmpty().IsEqual("xxx").Throw();
// Which means - when stringArgument is null or empty OR is equal to "xxx" we will throw exception. If it is null, we will throw ArgumentNullException. If it is equal to "xxx", we will throw ArgumentException.

Resources