훅의 이름을 알려 주서 예제를 계속하겠습니다. 이것은 모든 콜백 코드가 듣기 위해 사용해야하는 이름입니다. 다시 말하지만, 다른 언어는이 설정을 "이벤트"라고합니다. 따라서 더 많은 것을 배우려면 주어진 언어로 찾아보십시오.
우리는 후크 추가 _user라고 부를 것입니다. 단순하고 바로 요점까지 생각하지 않습니까? 이름이 있으면이 후크를 부를 위치를 결정할 수 있습니다. 성공적인 삽입 직후에 좋은 생각이 될 것 같아요 :
이제 우리는 adds_user hook 또는 전혀 듣지 않는 수십 개의 콜백 함수를 가질 수 있습니다. 어쩌면 우리는 사용자를 Zendesk에 삽입 할 책임이있는 콜백이 있고 이름과 나이를 가져 와서 마케팅에 이메일을 생성하는 다른 콜백이있을 수 있습니다. 이 "가입자"코드는 API 프로젝트 내부의 hooks.php 코드를 볼 수있는 한 코드베이스의 다른 곳에서 살 수 있습니다. 일반적으로 콜백 함수를 별도의 파일에 넣고 해당 파일도 API에 포함시킵니다. 아래는 이제 우리가 만든이 새로운 후크를 활용할 수있는 콜백의 한 예입니다.<span>// Global array which will hold all of our hooks
</span><span>// We will reference this array in each function to add/remove/call our hooks
</span><span>// The code below should also be seen by any callbacks we write for the system later.
</span><span>$hooks = [];
</span>
<span>// Below are global functions that can be seen from our API code
</span><span>// The add_hook method will allow us to attach a function (callback) to a given event name
</span><span>function add_hook($event_name, $callback) {
</span> <span>global $hooks;
</span>
<span>if ($callback !== null) {
</span> <span>if ($callback) {
</span> <span>// We can set up multiple callbacks under a single event name
</span> <span>$hooks[$event_name][] = $callback;
</span> <span>}
</span> <span>}
</span><span>}
</span>
<span>// Super easy to implement, we remove the given hook by its name
</span><span>function remove_hook($event_name) {
</span> <span>global $hooks;
</span>
<span>unset($hooks[$event_name]);
</span><span>}
</span>
<span>// When we want to trigger our callbacks, we can call this function
</span><span>// with its name and any parameters we want to pass.
</span><span>function do_hook($event_name, ...$params) {
</span> <span>global $hooks;
</span>
<span>if (isset($hooks[$event_name])) {
</span> <span>// Loop through all the callbacks on this event name and call them (if defined that is)
</span> <span>// As we call each callback, we given it our parameters.
</span> <span>foreach ($hooks[$event_name] as $function) {
</span> <span>if (function_exists($function)) {
</span> <span>call_user_func($function, ...$params);
</span> <span>}
</span> <span>}
</span> <span>}
</span><span>}
</span>
우리는이 고리를 어디에 놓을 수 있습니까?
위의 코드에서 우리는 단일 엔드 포인트의 후크를 사용하는 것을 보여줍니다. 이 후크는 /adduser 엔드 포인트가 호출되고 인서트가 성공한 후에 만 트리거됩니다. 그러나 이것이이 후크를 사용할 수있는 유일한 곳은 아닙니다. API 클래스에 API 키가 유효한지 확인하거나 특정 유형의 요청을 받았는지 확인하는 API 클래스에 라우팅 코드가있을 수 있습니다.
아래 이미지는이 모든 것이 건축 적으로 어떻게 보이는지에 대한 다이어그램입니다.