I've learned most of my OOP practices from C#, and coded php primarily in MVC but without custom objects for data types (user information and such I primarily stored in associative arrays). I'm wanting to take what I've learned in C# (making structs, or data classes basically, to store specific types of data, such as a user record, or say an article's information) into php. This is so I can know exactly what data values to expect (because they're defined fields, instead of just added to an array), allowing a bit more abstraction between controller and view.
Is there a certain way to do this in php, and in the MVC design pattern specifically? I am curious where I should put the definitions of these new "data types."
Or am I just thinking about this in the wrong way, and there is a better way to do it?
EDIT: A C# example of what I'm trying to accomplish:
class program1
{
public void main ()
{
Article randomArticle = getArticle (); //instead of returning an object array, it returns a defined data type with predefined fields, so I don't need to guess what's there and what isn't
Console.WriteLine(randomArticle.title);
Console.ReadLine();
}
public Article getArticle ()
{
return new Article("Sometitle", "SomeContent");
}
}
struct Article
{
public Title {get; private set;}
public Content {get; private set;}
public Article (string title, string content)
{
this.Title = title;
this.Content = content;
}
}
(idk if the above actually would compile, but it gives you the gist of what I'm attempting to do in PHP)
PHP is free of any logic you would like to implement. IMO, Ensuring data-types leads to a field of validations. I want you to check few terms, that will give you everything required.
Type Casting/ Juggling [docs here]
Casting is probably fastest way to stop unwanted input. The casts allowed are:
PHP Filters
PHP has a function filter_var (http://www.php.net/manual/en/function.filter-var.php) will helps you to compare a data type
var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
PHP inbuild() functions
They are many functions in php, which can help you check the data types
and many more
Regex Validation
You will be able to find many resources on this on the internet.
Your above method might turn into something like this
public function Article($title, $content) {
if(is_string($title)) { $this -> title = $title; }
if(is_string($content)) { $this -> content = $content; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With