2030 Engineer

[PHP] 리팩토링 (require) 본문

WEB/PHP

[PHP] 리팩토링 (require)

Hard_Try 2020. 5. 14. 21:22

php를 여러개, 이 뿐만 아니라 html, css 등도 코딩할 때 중복되는 내용이 여기저기 붙어있다면 

전체적으로 봤을 때 코드가 더러워 보이기도 하고 효율적이지 않다.

 

require함수는 이러한 문제를 해결해준다.

 

require_once라는 함수도 있는데 이 once가 붙으면 한 번만 참조를 한다는 의미로 만약 리팩토리 php내에서 

한 번 쓰인 중복된 php를 아래 코드에 또 있는 경우 중복되서 사용되지 않게끔 하기 위해서 

require_once를 사용한다. 

 

1. index.php

 

<?php
    require_once('../lib/print.php');
    require_once('../view/top.php');
?>
    <a href="create.php">create</a>
    <?php if(isset($_GET['id'])) { ?>
    <a href="update.php?id=<?=$_GET['id']?>">update</a>
    <form action="delete_process.php" method="post">
        <input type="hidden" name="id" value="<?=$_GET['id']?>">
        <input type="submit" value="delete">
    </form>
    <?php } ?>
    <h2>
      <?php
      print_title();
      ?>
    </h2>
    <?php
    print_description();
     ?>
<?php
require_once('../view/bottom.php');
?>

 

전의 포스트인 CRUD의 코드보다 훨씬 간결하게 나타난다.

 

 

2.  top.php

 

<?php
require_once('../lib/print.php');
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      <?php
      print_title();
      ?>
    </title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <ol>
      <?php
      print_list();
      ?>
    </ol>

 

여기서 require_once를 사용해야 하는 이유가 등장한다. 

 

print.php의 코드를 살펴보자

 

<?php
function print_title(){
  if(isset($_GET['id'])){
    echo $_GET['id'];
  } else {
    echo "Welcome";
  }
}
function print_description(){
  if(isset($_GET['id'])){
    echo file_get_contents("../data/".$_GET['id']);
  } else {
    echo "Hello, PHP";
  }
}
function print_list(){
  $list = scandir('../data/');
  $i = 0;
  while($i < count($list)){
    if($list[$i] != '.') {
      if($list[$i] != '..') {
        echo "<li><a href=\"index.php?id=$list[$i]\">$list[$i]</a></li>\n";
      }
    }
    $i = $i + 1;
  }
}
?>

 

print.php안에 print_list()가 존재한다. 하지만 top.php에서 우선적으로 쓰였으며 일반적인 require을 썼다면 여러번 호출 되어 중복 오류가 떴을 것이다. 따라서 require_once를 씀으로써 한 번만 호출함으로써 이러한 오류가 나지 않게 끔 해주는 것이다.

 

 

3. bottom.php

 

</body>
</html>

 

이러한 작은 문구도 중복되는 것을 잡아주는 이유는

copyright라던가 아니면 공통적으로 마지막으로 들어갈 문구나 표시 내용을 유지 보수하기 위해 이 php만 쓰면 되므로

만들어 놓는게 좋다.

 

 

위의 것들이 완벽하게 리팩토링된 것은 아니다.

이렇게 함으로써 각 php마다의 간결성이 이전보다 나아졌다는 것은 가시적으로도 볼 수 있다.

'WEB > PHP' 카테고리의 다른 글

[PHP] Cross site scripting (XSS)  (0) 2020.05.18
[PHP] CRUD  (0) 2020.05.13
[PHP] 제어문, 조건문, 반복문  (0) 2020.05.08
[PHP] PHP 함수 활용  (0) 2020.05.07
[PHP] PHP의 원리  (0) 2020.04.23
Comments