Laravel model properties - laravel-5

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?

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 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.

Rhino Mocks Func asserting Test

I need to test that a particular Func is called in Method List ex:
public class ProductController : BaseController
{
private readonly Func<IProductRepository> prodRepo;
public ProductController(Func<IProductRepository> _prodRepo)
{
prodRepo = _prodRepo;
}
public ActionResult List(string applicationID)
{
var products = prodRepo().GetForApp(applicationID).ToList();
return PartialView("_List",products);
}
}
in this case i need to verify that prodRepo().GetForApp(applicationID) whase called.
Do you really need to verify that the Func is called? Or do you need to verify that the ProductController retrieves the products correctly?
If it's the latter, just set up a mock of the IProductRepository to return some products, pass it in via a lambda, and assert that the products you get are the right ones. Generally, if something is providing information (the "arrange" phase in act / arrange / assert, or the "given" in given / when / then) then you want a stub rather than a mock.
The only time you really need to use a mock and verify that something has been called is when the class under test is delegating a responsibility - for instance, saving a product in the repository.
Also, please check out Moq... it's a bit easier to set up stubs in Moq IMO.
I advice you to write your test in Arrange-Act-Assert style. You could read more at Ayende's blog
Arrange phase
First define MockRepository and expectations:
var mockRepository = new MockRepository();
var repository = mockRepository.StrictMock<IProductRepository>();
using(mockRepository.Record())
{
repository.Expect(x => x.GetForApp(Arg<string>.Is.Anything)).Return(new string[0]).Repeat.Once();
}
var productController = new ProductController((Func<IProductRepository>)(() => repository));
Act phase
Perform action:
productController.List("testApplicationID");
Assert phase
Verify results:
repository.VerifyAllExpectations();
Missing interface IProductRepository
public interface IProductRepository
{
IEnumerable<string> GetForApp(string applicationID);
}

Facade Pattern, is this ok?

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.

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