3
\$\begingroup\$

I am new user of CodeIgniter and I am trying to build an application that there are lots of jQuery dynamical content.

Below I provide a code that I am using in order to be precise. The code below is running and I cannot see any problem. However, since I will be using pieces of code like this in several different parts of my application, I would like to know if this is a good design. If it is not, please let me know how to proceed.

The code below basically describe a search form in which the results are dynamically included.

This is my view:

<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("form#searchForm").submit(function() {
                    var theCity = $("select#chooseCity").val(); 
                    $.post("welcome/searchPeopleResults/", {theCity: theCity}, function(data) {
                        $("div#searchResults").html(data);
                    });
                  return false
                });
            });
        </script>
    </head>

    <body>


        <FORM id="searchForm">
            <h2>Selecione uma cidade: </h2>            
            <select id="chooseCity">
                <?php
                $theCitiesOptionsHTML = "cityOptions.html"; <!-- A large list of cities -->
                require($thePathDataFiles.$theCitiesOptionsHTML);                
                ?> 
            </select>
        </FORM>
        <div id="searchResults">
            <!-- Search results should arise here -->
        </div>        

     </body>

</html> 

This is my controller:

   class Welcome extends CI_Controller {

        public function index()
        {
                    $this->load->view('searchPeople');
                    $this->load->view('css/format');
        }
            public function searchPeopleResults(){
                $theCity=$this->input->post('theCity');
                $this->load->model('MSearchPeople');
                $data=$this->MSearchPeople->provideSearchPeopleResults($theCity);
                echo $data;
            }
    }

This is my model:

Class MSearchPeople extends CI_Model {

    function provideSearchPeopleResults($theCity) {

    // Here I got my database query ($theUsername, $theFirstName, $theLastName, $theSummary) and call the function presented below  "writeHtmlSearchPeople".    

     return $theHtml;

    }
}

Note that that after querying the database, the model above generates the necessary pieces of HTML code to be returned to the scope of the $.ṕost() function.

Precisely, inside the function provideSearchPeopleResults($theCity), I call another function that generates the html code for me. Something like that:

<?php

function writeHtmlSearchPeople($theUsername, $theFirstName, $theLastName, $theSummary) {

    $theCompleteName = $theFirstName . " " . $theLastName;
    $theFigureName = base_url() . "application/views/photos/" . $theUsername;

    ?>



    <table border = "0" width = "75%">
        <tr>
            <td width = "20%">
                <img src="<?php echo $theFigureName ?>" alt=" " width= "150"> 
            </td>
            <td width = "80%">
                <a class="supplierPage" data-username="<?php echo $theUsername ?>" href = "" > "<?php echo $theCompleteName ?>"</a> "<?php echo $theSummary ?>"



            </td>
        </tr>
    </table>




<?php

    }
    ?>

I am particularly worried with the fact that I am generating HTML code from my model (note that this HTML code is just being returned as data to the scope of the $post() function). However, I am not sure if there is a better practice for this!

Furthermore, I would like to implement explicitly the MVC design. Although views and models are in different files, they are not connected by the controller.

\$\endgroup\$
1
  • \$\begingroup\$ I would suggest that you use a templating framework (ex: handlebar just to name one) in the client side and simply send json instead of html in your ajax calls/ api.Also, I really recommend people using jQuery for what it is a library not a framework. If you plan on building an app that can grow. Go for a framework. \$\endgroup\$ Commented Feb 19, 2014 at 1:59

1 Answer 1

2
\$\begingroup\$

You are right with your concerns regarding the model rendering the output. But you're almost there ain't you? Why don't you let your model return the data instead of the HTML-Code and let the controller call writeHtmlSearchPeople:

class MSearchPeople extends CI_Model {
    function provideSearchPeopleResults($theCity) {
        $result = // db query, normalize data,
        return $result;
    }
}

class Welcome extends CI_Controller {
    public function searchPeopleResults() {
        $theCity = $this->input->post('theCity');
        $this->load->model('MSearchPeople');
        $data = $this->MSearchPeople->provideSearchPeopleResults($theCity);
        echo writeHtmlSearchPeople($data); // or however you rendered the data
    }
}

Now this the controller acts as the mediator between your view and your model. In my opinion it is important that the controller never contains any view logic besides returning or echo-ing it. If the data from your model requires iterations, put these in your view.

Other remarks:

  • I don't know CI, yet you might want to check to validate your input ($theCity) for invalid values and react accordingly
  • Code Style:
    • Class MSearchPeople, the class keyword probably should be lower-case
    • Indentation: might be a copy & paste problem, though try to keep it consistent.
    • Whitespaces in assignments: More of a personal thing though widely used: a whitespace before and after an assignment operator: $theCity = $this->input->post('theCity');. Makes it easier to read.
  • Variable & class naming: probably the second most difficult things in programming (after writing comments). Maybe you can find better names for your variables and names? Some examples:
    • Welcome Controller? What is it's responsibility? I really can't tell in what way it has to do with welcoming whatever being.
    • $theCity=$this->input->post('theCity'); This name indicates for me a one valid city entity. But rather more ain't it the current $searchTerm? In general I'd consider variables starting the the very bad practice. The in a name would indicate the final single entity resulted from a long journey. But even then I'd skip the the as it puts too much emphasis on the the and not on the following object. I'd go with $matchingCities instead.
    • I'd consider the hungarian notation obsolete in typed languages (MSearchPeople => SearchPeople) (bluntly assumung that the M stands for Model).
    • provideSearchPeopleResults this name indicates that this information is made available by other means and not returned. The common pattern when returning data is get -> getSearchPeopleResults. As this function is called on the MSearchPeople model, the SearchPeople part in this function name is duplicate information too. The function name could be shortened to search.
  • While I only know very little of your code, I'd consider search part of either the People model or better, repository. There is no need for a dedicated model for searching. Of course this highly depends on the business model you are modeling.
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Thank you for your answer. I expected this kind of answer. The point is that as you assume the data may have lots of results and I would have to transfer this to the view. On other hand, I also was influenced by stackoverflow.com/questions/13813046/…. What do you think about this? Thank you for the other suggestions, but most of them are related to CodeIgniter style: "Welcome", "MSearchModel". In fact, this is just a part of a large application and there are several "search" situations. \$\endgroup\$ Commented Feb 19, 2014 at 2:05
  • \$\begingroup\$ Don't worry about this "transfering", this won't impose any performance problems as PHP optimizes this on it's own. Furthermore don't let your architecture be driven by premature optimization. You can optimize later on if this really turns out to be a bottleneck (which I highly doubt it will ever be). The author of the post is right. And in my opinion what you use is a model is a mixture of a model, repository and mapper (violating the single responsibility principle of course). On the View accessing model discussion: I don't like the view depending on the model. ViewModels come to mind here. \$\endgroup\$
    – Fge
    Commented Feb 19, 2014 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.