首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Codeigniter 3 CMS (博客)应用程序

Codeigniter 3 CMS (博客)应用程序
EN

Code Review用户
提问于 2020-04-12 16:19:13
回答 1查看 409关注 0票数 1

我正在使用Codeigniter 3.1.8和Bootstra4编写一个基本的博客应用

应用程序有用户(作者)和帖子(文章)。每一篇文章:

  • 有个作家,
  • 属于一个类别,
  • 具有默认(泛型)主图像,除非作者为其指定特定的图像,否则将显示该图像。

员额表的结构如下:

我有兴趣评估我为创建、更新和删除操作编写的代码的质量。另外,在岗位形象管理方面。

在邮政总监中,我有:

代码语言:javascript
复制
public function create() {

    // Only logged in users can create posts
    if (!$this->session->userdata('is_logged_in')) {
        redirect('login');
    }

    $data = $this->get_data();
    $data['tagline'] = "Add New Post";

    if ($data['categories']) {
        foreach ($data['categories'] as &$category) {
            $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
        }
    }

    $this->form_validation->set_rules('title', 'Title', 'required');
    $this->form_validation->set_rules('desc', 'Short description', 'required');
    $this->form_validation->set_rules('body', 'Body', 'required');
    $this->form_validation->set_error_delimiters('', '');

    if($this->form_validation->run() === FALSE){
        $this->load->view('partials/header', $data);
        $this->load->view('dashboard/create-post');
        $this->load->view('partials/footer');
    } else {
        // Create slug (from title)
        $slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
        $slugcount = $this->Posts_model->slug_count($slug, null);
        if ($slugcount > 0) {
            $slug = $slug."-".$slugcount;
        }

        // Upload image
        $config['upload_path'] = './assets/img/posts';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['max_size'] = '2048';

        $this->load->library('upload', $config);

        if(!$this->upload->do_upload()){

            $errors = array('error' => $this->upload->display_errors());

            // Dysplay upload validation errors 
            // only if a file is uploaded and there are errors
            if (empty($_FILES['userfile']['name'])) {
                $errors = [];
            }

            if (empty($errors)) {
                $post_image = 'default.jpg';
            } else {
                $data['upload_errors'] = $errors;
            }

        } else {
            $data = array('upload_data' => $this->upload->data());
            $post_image = $_FILES['userfile']['name'];
        }

        if (empty($errors)) {
            $this->Posts_model->create_post($post_image, $slug);
            $this->session->set_flashdata('post_created', 'Your post has been created');
            redirect('/');
        } else {
            $this->load->view('partials/header', $data);
            $this->load->view('dashboard/create-post');
            $this->load->view('partials/footer');
        }
    }
}

public function edit($id) {
    // Only logged in users can edit posts
    if (!$this->session->userdata('is_logged_in')) {
        redirect('login');
    }

    $data = $this->get_data();
    $data['post'] = $this->Posts_model->get_post($id);

    if (($this->session->userdata('user_id') == $data['post']->author_id) || $this->session->userdata('user_is_admin')) {
        $data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
        $this->load->view('partials/header', $data);
        $this->load->view('dashboard/edit-post');
        $this->load->view('partials/footer');
    } else {
        /* If the current user is not the author
        of the post do not alow edit */
        redirect('/' . $id);
    }
}

public function update() {
    // Form data validation rules
    $this->form_validation->set_rules('title', 'Title', 'required',  array('required' => 'The %s field can not be empty'));
    $this->form_validation->set_rules('desc', 'Short description', 'required',  array('required' => 'The %s field can not be empty'));
    $this->form_validation->set_rules('body', 'Body', 'required',  array('required' => 'The %s field can not be empty'));
    $this->form_validation->set_error_delimiters('', '');

    $id = $this->input->post('id');

    // Update slug (from title)
    if ($this->form_validation->run()) {
        $slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
        $slugcount = $this->Posts_model->slug_count($slug, $id);
        if ($slugcount > 0) {
            $slug = $slug."-".$slugcount;
        }
    } else {
        $slug = $this->input->post('slug');
    }

    // Upload image
    $config['upload_path'] = './assets/img/posts';
    $config['allowed_types'] = 'jpg|jpeg|png';
    $config['max_size'] = '2048';

    $this->load->library('upload', $config);

    if (isset($_FILES['userfile']['name']) && $_FILES['userfile']['name'] != null) {
        // Use name field in do_upload method
        if (!$this->upload->do_upload('userfile')) {

            $errors = array('error' => $this->upload->display_errors());

            // Display upload validation errors 
            // only if a file is uploaded and there are errors
            if (empty($_FILES['userfile']['name'])) {
                $errors = [];
            }

            if (!empty($errors)) {
                $data['upload_errors'] = $errors;
            }

        } else {
            $data = $this->upload->data();
            $post_image = $data['raw_name'].$data[ 'file_ext'];
        }
    }
    else {
        $post_image = $this->input->post('postimage');
    }

    if ($this->form_validation->run() && empty($errors)) {
        $this->Posts_model->update_post($id, $post_image, $slug);
        $this->session->set_flashdata('post_updated', 'Your post has been updated');
        redirect('/' . $slug);
    } else {
        $this->form_validation->run();
        $this->session->set_flashdata('errors', validation_errors());
        $this->session->set_flashdata('upload_errors', $errors);
        redirect('/dashboard/posts/edit/' . $slug);
    }
}

public function delete($slug) {
    // Only logged in users can delete posts
    if (!$this->session->userdata('is_logged_in')) {
        redirect('login');
    }

    $data['post'] = $this->Posts_model->get_post($slug);
    if (($this->session->userdata('user_id') == $data['post']->author_id) || $this->session->userdata('user_is_admin')) {
        $this->Posts_model->delete_post($slug);
        $this->session->set_flashdata('post_deleted', 'The post has been deleted');
        redirect('/');
    } else {
        /* If the current user is not the author
        of the post do not alow delete */
        $this->session->set_flashdata('no_permission_to_delete_post', 'You are not authorized to delete this post');
        redirect('/' . $slug);
    }
}

public function deleteimage($id) {
    $this->load->model('Posts_model');
    $this->Posts_model->delete_post_image($id);
    redirect($this->agent->referrer());
}

在Posts_model模型中:

代码语言:javascript
复制
// Create, post
public function create_post($post_image, $slug) {
    $data = [
        'title' => $this->input->post('title'),
        'slug' => $slug,
        'description' => $this->input->post('desc'),
        'content' => $this->input->post('body'),
        'post_image' => $post_image,
        'author_id' => $this->session->userdata('user_id'),
        'cat_id' => $this->input->post('category'),
        'created_at' => date('Y-m-d H:i:s')
    ];
    return $this->db->insert('posts', $data);
}

// Update post
public function update_post($id, $post_image, $slug) {
    $data = [
        'title' => $this->input->post('title'),
        'slug' => $slug,
        'description' => $this->input->post('desc'),
        'content' => $this->input->post('body'),
        'post_image' => $post_image,
        'cat_id' => $this->input->post('category'),
        'updated_at' => date('Y-m-d H:i:s')
    ];

    $this->db->where('id', $id);
    return $this->db->update('posts', $data);
}

//Delete post
public function delete_post($slug) {
    $this->db->where('slug', $slug);
    $this->db->delete('posts');
    return true;
}

public function delete_post_image($id) {
    $this->db->update('posts', array('post_image'=>'default.jpg'), ['id'=>$id]);
}

create-post.php视图:

代码语言:javascript
复制
    load->view("dashboard/partials/sidebar-single");?>
    
      
        New Post
        
          

          
            
             
          

          
            
             
          

          
                          <?php echo set_value('body')?>
            
             
          

          
            
              
                name; ?>
              
            
          

          Upload an image
          
            
             
              
            
          

          
            
              
            
            
              Cancel

编辑-post.php视图:

代码语言:javascript
复制
    load->view("dashboard/partials/sidebar-single");?>
    
      
        Edit post
        

          session->flashdata('errors')) {
           $errors = $this->session->flashdata('errors');
           echo '' . "\n";
           echo '×' . "\n";
           echo $errors;
           echo 'We have restored the post.';
           echo '';
         } ?>

         
         
         

         
          
           
        

        
          
           
        

        
          <?php echo $post->content; ?>
           
        

        
          
            
              id == $post->cat_id): ?>
                name; ?>
                
                  name; ?>
                
              
            
          

          

          Upload an image
          
             
            session->flashdata('upload_errors')) {
              if ($this->session->flashdata('upload_errors')) { ?>              
                
                  
                
              
          

          
            
              
            
            
              Cancel

侧栏-single.php部分(显示post图像):

代码语言:javascript
复制
    Featured Image
    
      post_image) && $post->post_image !== 'default.jpg'): ?>
        
      
        
      
    
    
      post_image) && $post->post_image !== 'default.jpg' ? 'data-pid="' . $post->id . '"' : '' ?> id="postImage" class="smooth-scroll">
        post_image) && $post->post_image !== 'default.jpg' ? 'Delete' : 'Add' ?> image

文章删除是通过jQuery Ajax实现的:

代码语言:javascript
复制
//Delete Posts
$('.delete-post').on('click', function(evt){
    evt.preventDefault();
    var deleteUrl = $(this).attr('href');
    var slug = $(this).data('slug');
    var postsCount = Number($("#posts_count").text());

    if(confirm('Delete this post?')) {
      if ($(this).hasClass("ajax-btn")) {
        $.ajax({
          url: baseUrl + '/dashboard/posts/delete/' + slug,
          method: 'GET',
          dataType: 'html',
          success: function(deleteMsg){
            postsCount = postsCount - 1;
            $('tr[data-slug="' + slug +'"]').fadeOut('250');
            $("#posts_count").text(postsCount);
            $('#post_delete_msg').text("The post has been deleted");
            $('#post_delete_msg').slideDown(250).delay(2500).slideUp(250);
          }
        });
      } else {
        window.location.href = deleteUrl;
      }
    }
});

post映像管理(更确切地说,删除当前的post映像)还使用了jQuery Ajax:

代码语言:javascript
复制
$('#postImage').on('click', function(evt){
    evt.preventDefault();

    if (this.hash === "") {
      var $this = $(this);
      var $postImage = $this.closest('.card').find('img');
      var $hiddenPostImage = $('input[name="postimage"]');
      var defaultPostImage = baseUrl + 'assets/img/posts/default.jpg';

      //Get post ID
      var id = $(this).data('pid');

      if(confirm("Delete the post's featured image?")) {
        $.ajax({
          url: baseUrl + 'dashboard/posts/deleteimage/' + id,
          method: 'GET',
          dataType: 'html',
          success: function(deleteMsg){
            $postImage.attr('src', defaultPostImage);
            $hiddenPostImage.val(defaultPostImage);
            $this.text('Add image');
            $this.attr('href', '#imageUploader');
          }
        });
      }
    }
});

我怎么能做得更好呢?)

EN

回答 1

Code Review用户

回答已采纳

发布于 2020-04-14 00:03:14

使用实体来表示域关注点和业务规则。

使用存储库与数据库合并。

升级到CodeIgniter 4

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/240400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档