3

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)

Jess
  • 8,628
  • 6
  • 49
  • 67

2 Answers2

2

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.

  1. Type Casting/ Juggling [docs here]

    Casting is probably fastest way to stop unwanted input. The casts allowed are:

    • (int), (integer) - cast to integer
    • (bool), (boolean) - cast to boolean
    • (float), (double), (real) - cast to float
    • (string) - cast to string
    • (array) - cast to array
    • (object) - cast to object
    • (unset) - cast to NULL (PHP 5)
  2. 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('bob@example.com', FILTER_VALIDATE_EMAIL));
    var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
    
  3. PHP inbuild() functions

    They are many functions in php, which can help you check the data types

    • is_array(): checks array
    • is_integer(): Check integer
    • is_object(): Check objects
    • is_float(): Checks Floating point number
    • ctype_digit(): Checks Integer

    and many more

  4. Regex Validation

    You will be able to find many resources on this on the internet.


Other Resources


Update

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; }
}
Starx
  • 77,474
  • 47
  • 185
  • 261
  • Hm, it seems I haven't conveyed my question well enough. I'm just looking for a way to replace an associative array of values (whose key count and names can change) to a more structured object (whose key count and names can not change) so that when I pass that information around I don't need to guess if a value is present or not. I could add examples of what I'm saying in C#, if that might help at all? – Jess Mar 01 '12 at 04:38
  • @mazzzzz, Oh. I answered `where I should put the definitions of these new "data types."` and yes, examples would be helpful – Starx Mar 01 '12 at 04:43
  • Alright, I added a quick example, hope it explains it a bit better then I could – Jess Mar 01 '12 at 04:50
  • @mazzzzz, thats where the type casting comes in – Starx Mar 01 '12 at 04:59
1

In PHP, you are free to write your own systems that accomplish MVC. Instead of rolling your own to start, though, I suggest looking into using an existing system. There's a huge ecosphere of us php types, and a long history. By some opinions, PHP is more well-established than a younger and faster evolving C#. It's also simpler, which is nice. Specifically, though: CakePHP is one I'd recommend. Drupal is more robust. And there's always Zend. Advantage of going Zend is the end-to-end solution from the editor to the server optimization and security.

p.s. c# is more mvvm

EDIT: code example

class Article {

    protected $_title;
    protected $_content;

    public function setTitle( $title ) {
        $this->_title = $title;
    }
    public function setContent( $content ) {
        $this->_content = $content;
    }

    public function getTitle() {
        return $this->_title;
    }
    public function getContent() {
        return $this->_content;
    }

    /* magic not advisable; a technically valid technique, though it can lead to problems
    public function __get( $property ) {
        switch( $property ) {
            case 'title': return $this->_title; break;
            case 'content': return $this->_content; break;
            default: break;
        }
    }
    */

}
zvnty3
  • 59
  • 4
  • Not sure exactly what you mean. I'm currently working with two MVC systems, one being CodeIgniter, another being a very small one (called crumb). That aside, the both work on the standard principals of MVC. So my question was how would I integrate custom data type classes that would be returned from my models into a MVC pattern? – Jess Mar 01 '12 at 04:26
  • I stand by the recommendation for CakePHP. However, it is weakest in the View area. You could probably implement another template system like Smarty, etc, though. I'm not sure what your proficiency level is with PHP. Drupal is a bigger beast and imo less friendly to newcomers. Cake is strong on the model side, especially if you don't have ultra-complex data. Synopsis: install and play with an established system, because with PHP you're kinda on your own. Making a good decision helps a lot, too, if the project will be getting big. – zvnty3 Mar 01 '12 at 04:36
  • @Starx is pointing out minutia, when I feel like you need bearings on how to approach the whole world of PHP, hence my talk of frameworks. – zvnty3 Mar 01 '12 at 04:38
  • @mazzzzz Seeing more from your comment on Starx's answer, what I'd recommend is to implement forced setters if not getters (functions) for all private/protected data within your classes. That accomplishes the basic premise. My answer here was more on the larger MVC issue. CakePHP facilitates data to the db, but you could add the support for data setting and value validation/enforcement. – zvnty3 Mar 01 '12 at 04:43
  • Fair enough, I've coded php for years though. The issue I'm having is approaching the area of OOP in php (for which I have little to no knowledge), and some of the more advanced topics of OOP in general. Though thank you for the recommendations. – Jess Mar 01 '12 at 04:43
  • If example code is in order, I can dig something up and edit the answer. I just mean if you have a protected `var $_name;` you make a function method like `$obj->set_name()` which runs whatever validation logic you need. – zvnty3 Mar 01 '12 at 04:45
  • [simple example](http://stackoverflow.com/questions/3782688/getters-and-setters-in-php) – zvnty3 Mar 01 '12 at 04:46
  • Hopefully the added example code will give you an idea of what I'm looking for, and you can help me understand the best way to do it in PHP. – Jess Mar 01 '12 at 04:52
  • well, I do use c# a lot, so it helps some. however, did you look at the above example link? – zvnty3 Mar 01 '12 at 05:00
  • here should be an of CakePHP that responds to your `instead of returning an object array` comment in your example code. CakePHP does exactly that in its model system. well, mostly on the getting. underneath the hood, objects in php can often be analogous to a propertybag array. it's not strict like c# at all. keep looking into these things, I think you'll be encouraged. – zvnty3 Mar 01 '12 at 05:01
  • another useful [link](http://www.sitepoint.com/application-development-cakephp/) - takes a longer read, but note the comment in there a ways that `You are now able to create, update, delete and display your notes with (literally) five lines of PHP code!` Cake is nice. – zvnty3 Mar 01 '12 at 05:05
  • edited to add example code. this addresses an Article class. look in the php doc for [__get()](http://www.php.net/manual/en/language.oop5.overloading.php#object.get) magic method - reasons not to use it are many (except for rapid development as noted in a link above). difference with c# is you can't make a property public to get but protected to set, either the property is public or not. hopefully this is starting to make more sense. – zvnty3 Mar 01 '12 at 05:19
  • @mazzzzz care to comment on whether or not this helped? and accept an answer that did? – zvnty3 Mar 06 '12 at 22:44