duanhe6799 2011-04-23 13:04
浏览 20
已采纳

日历应用程序 - 输出该月的日期

I'm working on a calendar/planner application and I need some advice.

I'm working on the following part of my application:

days of the month

It shows the days of the month from 1 till the end of the month, 28/29, 30 or 31. I achieved this.. (here) but my code is extremely ugly and I'm sure there must be another way to do this.

I'm working in CodeIgniter. My controller contains the following function to populate the list with the days of the month:

    public function init_days()
{
            // post values? in case of previous/next months (ajax)
    if($this->input->post('post_month') && $this->input->post('post_year'))
    {
        $month = $this->input->post('post_month');
        $year = $this->input->post('post_year');
        $data = $this->planner_model->calendar_data($month, $year);
    }
    else
    {
        $data = $this->planner_model->calendar_data();
    }

    // init empty calendar
    $data['calendar'] = '';

    // easy var names
    $current_month = $data['current_month'];
    $current_year = $data['current_year'];

    // echo list into $data['calendar']
    for($i = 1; $i <= $data['days_in_month']; $i++)
    {
        if($current_month == date('n') && $current_year == date('Y'))
        {
            if($i < $data['current_day_of_month'])
            {
                $data['calendar'] .= "<li class='prev_month' value='$i'>$i</li>";
            }
            if($i == $data['current_day_of_month'])
            {
                $data['calendar'] .= "<li class='today' value='$i'>$i</li>";
            }
            if($i > $data['current_day_of_month'])
            {
                $data['calendar'] .= "<li class='next_month' value='$i'>$i</li>";
            }
        }
        if( ($current_month > date('n') && $current_year == date('Y')) || ($current_year > date('Y')) )
        {
            $data['calendar'] .= "<li class='next_month' value='$i'>$i</li>";
        }
        if( ($current_month < date('n') && $current_year == date('Y')) || ($current_year < date('Y')) )
        {
            $data['calendar'] .= "<li class='prev_month' value='$i'>$i</li>";
        }
    }
    $data['month_name'] = ucfirst($this->get_month_name($current_month));

    header('Content-type: application/json');
    echo json_encode($data);
}

My model returns the $data array that gets called by the controller (in the else clause, first part):

    public function calendar_data($month = '', $year = '')
{
    if( ! empty($month) && ! empty($year))
    {
        $data['current_year'] = $year;
        $data['current_month'] = $month;
        $data['current_day_of_month'] = date('j');
        $data['current_day_of_week'] = date('w');
        $data['days_in_month'] = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    }
    else
    {
        $data['current_year'] = date('Y');
        $data['current_month'] = date('n');
        $data['current_day_of_month'] = date('j');
        $data['current_day_of_week'] = date('w');
        $data['days_in_month'] = cal_days_in_month(CAL_GREGORIAN, $data['current_month'], $data['current_year']);
    }


    return $data;
}

I then output this in my view with an AJAX call on $(document).ready.

$("#day_list").html(data['calendar']).fadeIn();

I'm not happy with the code. It's a mess, and I'm fairly sure I'm breaking MVC here; aren't I? Could someone perhaps give some advice or insights on how to do this in a 'better' way? Thanks a lot.

The full source is here in case anyone would be kind enough to look through it and tell me if there's other stuff I'm doing wrong.

  • 写回答

1条回答 默认 最新

  • dtufl26404 2011-04-23 13:44
    关注

    The problem with MVC and the web is you can never really have clear delineation between the view and the controller. That's just the inherent nature of the web. I am more of a CakePHP guy, but the principles are the same. When I write my code, I always ask myself a handful of questions to know the best place to put my code.

    1. Am I retrieving, storing, or manipulating data? (if so, it's model)
    2. Am I displaying data or presenting data to the end-user? (if so, it's view).
    3. Everything else goes into my controller.

    That being said, with only taking a quick look at your code, it appears you are combing model code and view code in the controller, and that is why you feel uneasy about it. Here is some simple logic that may help you:

    Move all of the code that builds the list of dates into the model. Call it something like:

    function create_date_list() {
      // code here
    }
    

    This will only build an array of the dates you want to display. Keep in mind you can also pass things on the array like whether or not the date is a holiday, current day, weekend, etc. This will help you determine in the view how to format the date without having to add code to the view to do so. So for example, you may have an array that returned from the model that looks like this:

    [dates] {
      [22] {
         [day] => [Friday]
         [type] => [weekday]
      }
      [23] {
         [day] => [Saturday]
         [type] => [Weekend]
      }
      [24] {
         [day] => [Sunday]
         [type] => [Weekend]
         [Holiday] => [Easter]
      }
    }
    

    This may be overkill or not. But I used this example to show that the MODEL is where you do all of this heavy lifting, not the controller or the view.

    Next, build the view. I am not sure what it is in CodeIgniter, but in cake they are called Elements. These are snippets of view code that are available to any view (reusable view elements). So build a reusable view element that will take a date array, loop through it, and write the output in HTML. Notice how I can use the date array to format my view.

    <ul>
    <?php foreach($dates as $date): ?>
      <li class="date <?php echo $dates[$date]['type']; ?>><?php echo $date; ?></li>
    <?php endforeach; ?>
    </ul>
    

    Nice, clean, and concise. The advantage is if you ever want to change the look, you do not have to touch the controller. ;)

    Now, for the controller. Put the code in the controller that calls the date array from the model, and passes it to the view. The idea is FAT model, SKINNY view.

    function my_function() {
      // get code from model
      // set code for view
      // render view
    }
    

    While I haven't really "cleaned up" your code. I hope this gives you the guidance you were looking for on how to move the code around yourself so that a) it makes more sense to you and b) you can clean up the code in a way that will still conform to the MVC architecture you are striving for.

    Good luck and Happy Coding!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换