PhpStorm tips and tricks

Unknown
edited April 2018 in Dev & Ops

Fluent getter and setters the right way

  • Fluent setter:
    /**
     * Setter of ${PARAM_NAME}.
     *
     * @param ${TYPE_HINT} $${PARAM_NAME}
     * @return $this
     */
    public function set${NAME}(#if (${SCALAR_TYPE_HINT})${SCALAR_TYPE_HINT} #else#end$${PARAM_NAME})#if(${RETURN_TYPE})#else#end
    {
        $this->${FIELD_NAME} = $${PARAM_NAME};
        return $this;
    }
  • Getter Method:
    /**
     * Getter of ${FIELD_NAME}.
     *
     * @return ${TYPE_HINT}
     */
    public ${STATIC} function ${GET_OR_IS}${NAME}()#if(${RETURN_TYPE}): ${RETURN_TYPE}#else#end
    {
    #if (${STATIC} == "static")
        return self::$${FIELD_NAME};
    #else
        return $this->${FIELD_NAME};
    #end
    }
  • Setter method:
    /**
     * Setter of ${PARAM_NAME}.
     *
     * @param ${TYPE_HINT} $${PARAM_NAME}
     */
    public ${STATIC} function set${NAME}(#if (${SCALAR_TYPE_HINT})${SCALAR_TYPE_HINT} #else#end$${PARAM_NAME})
    {
    #if (${STATIC} == "static")
        self::$${FIELD_NAME} = $${PARAM_NAME};
    #else
        $this->${FIELD_NAME} = $${PARAM_NAME};
    #end
    }

Hot key is CMD + N ->

End results:

    /**
     * Getter of linkSession.
     *
     * @return bool
     */
    public function isLinkSession(): bool {
        return $this->linkSession;
    }

    /**
     * Setter of linkSession.
     *
     * @param bool $linkSession
     * @return $this
     */
    public function setLinkSession(bool $linkSession) {
        $this->linkSession = $linkSession;

        return $this;
    }

Comments

  • I just want to caution against using the self type hint. When you use subclasses or interface implementations that hint can restrict autocomplete. I've found it better to not type hint fluent calls but instead to use a docblock of @return $this.

  • Unknown
    edited April 2018

    @Todd said:
    I just want to caution against using the self type hint. When you use subclasses or interface implementations that hint can restrict autocomplete. I've found it better to not type hint fluent calls but instead to use a docblock of @return $this.

    I also had the same "revelation" since then.

  • I updated my above post.

  • Shortcuts

    • You can use the build in keyboard shortcuts ⌘+[ and ⌘+] to navigate back and forwards.
    • ⌘+Shift+a List all of the possible commands you can execute.
    • ⌘+O and ⌘+Shift+O jump to classes and files.