라라벨에서 custom helper 함수를 추가할 땐 “app/helpers/helper.php”와 같은 파일을 만들고 아래 json과 같이 그 파일을 composer.json에 “files”에 추가해주어야 한다.
"autoload": { "files": [ "app/helper/helpers.php" ], "classmap": [ "database/seeds", "database/factories" ], "psr-4": { "App\\": "app/" } }, "autoload-dev": { "psr-4": { "Tests\\": "tests/" } },
다만 하나의 file을 추가할 때는 괜찮아 보이지만 만약 추가해야하는 custom helper가 많아질 수록 관리도 힘들고 일일히 추가해야 하는 번거로움도 있다.
이럴때 폴더 단위로 app/Helpers/*
와 같이 로드되면 좋겠지만 composer의 files는 단일 파일만을 지원하며 * 와같이 여러 파일을 불러오는 기능은 존재하지 않는다.
(다만 class 와 관련되어선 사용할 수 있는것같다, 아마 namespace를 이용하지 않을까…?)
이럴때 app/helper/include.php
파일을 생성한 뒤 아래와 같이 작성해 준 뒤,
<?php $files = glob(__DIR__ . '/*.php'); if ($files === false) { throw new RuntimeException("Failed to glob for function files"); } foreach ($files as $file) { require_once $file; } unset($file); unset($files);
include.php
파일을 composer.json에 추가해준다.
"autoload": { "files": [ "app/helper/include.php" ], "classmap": [ "database/seeds", "database/factories" ], "psr-4": { "App\\": "app/" } }, "autoload-dev": { "psr-4": { "Tests\\": "tests/" } },
이후 composer dump-autoload
명령어를 통해 로드 해주면 app/helpers
폴더 안에 있는 모든 php 파일들에서 선언된 함수, 클래스들을 사용할 수 있다.