Swoft 容器使用

能夠藉助Swoft下的Bean類操做容器app

示例:this

將類綁定至容器url

use Swoft\Bean\Annotation\Bean; /** * @Bean("imageLogic") */
class ImageLogic extends BaseLogic { /** * 根據id獲取圖片 * @param int $id * @return array */
    public static function getOne(int $id): array { return Query::table(Image::class)->where('id',$id)->limit(1)->get(['url','thumb_url'])->getResult(); } }

從容器中取出對象:spa

方法一:注入code

use Swoft\Bean\Annotation\Inject; use App\Models\Logic\ImageLogic; class IndexController{ /** * @Inject("imageLogic") * @var ImageLogic */
    private $imageLogic; public function index() { $this->imageLogic->getOne(); } }

方法二:經過 BeanFactory 類獲取對象

use Swoft\Bean\BeanFactory; class IndexController { /** * @RequestMapping(route="index",method=RequestMethod::GET) */
    public function index(Request $request){ //判斷容器中是否存在該實例
        var_dump(BeanFactory::hasBean('imageLogic')); //從容器中獲取
        $bean = BeanFactory::getBean('imageLogic'); return $bean->getOne(); } }
相關文章
相關標籤/搜索