top | item 6793060

(no title)

moneyrich4 | 12 years ago

a primer on mvc

ill just give a easy to understand (?) example

MVC Model View Controller

    Model: this is a data model [access pattern]

    models/users.code:
        class User {
            function getUsers() {
                $db->fetchAll("SELECT * FROM USERS LEFT JOIN CRAZYTABLE ON CRAZYSTUFf = 1")
            }
        }

    Controller: Handles application logic

    controllers/userlist.code
        requires('models/user.code')
        function showUsers() {
            $users = User::getUsers()
            $usernames = []
            foreach($users as $row)
                $usernames[] = $row['name']

            renderView('views/userpage.html', $usernames)
            return
        }

    View: Display logic, ideally as simple as possible
    Could be a html template or a windows form
    Purists say you should do all data validation and preperation in the controller

    views/userpage.html
        <div id=myuserlist>
            <h1>Our users</h1>
            <ul>
                {{ foreach $users as $user }}
                    <li>{{ $user }}</li>
                {{ endforeach }}
            </ul>
        </div>
Now you understand MVC! =)

discuss

order

No comments yet.