项目作者: black-lamp

项目描述 :
Component for search in Active Record model
高级语言: PHP
项目地址: git://github.com/black-lamp/yii2-search.git
创建时间: 2016-09-19T15:25:33Z
项目社区:https://github.com/black-lamp/yii2-search

开源协议:BSD 3-Clause "New" or "Revised" License

下载


Component for search in Active Record model

Build Status
Latest Stable Version
Latest Unstable Version
License

Installation

Run command

  1. composer require black-lamp/yii2-search

or add

  1. "black-lamp/yii2-search": "^2.0.0"

to the require section of your composer.json.

Add ‘SiteSearch’ component to application config

  1. 'components' => [
  2. // ...
  3. 'search' => [
  4. 'class' => bl\search\SearchComponent::class,
  5. // models where you need the search
  6. 'models' => [
  7. 'article' => [
  8. 'class' => frontend\models\Article::class,
  9. 'label' => 'Articles'
  10. ],
  11. // ...
  12. ]
  13. ],
  14. ]

To models array you should to add the active record models where component will be make a search.

class it’s a model’s name.

label it’s a title for displaying in view.

  1. /**
  2. * @property integer $id
  3. * @property string $title
  4. * @property string $shortText
  5. * @property string $fullText
  6. * @property string $socialNetworksText
  7. */
  8. class Article extends ActiveRecord implements \bl\search\interfaces\SearchInterface
  9. {
  10. // ...
  11. /**
  12. * @inheritdoc
  13. */
  14. public function getSearchTitle() {
  15. return $this->title;
  16. }
  17. /**
  18. * @inheritdoc
  19. */
  20. public function getSearchDescription() {
  21. return $this->shortText;
  22. }
  23. /**
  24. * @inheritdoc
  25. */
  26. public function getSearchUrl() {
  27. return Url::toRoute["/articles/$this->id"];
  28. }
  29. /**
  30. * @inheritdoc
  31. */
  32. public function getSearchFields() {
  33. return [
  34. 'title',
  35. 'shortText',
  36. 'fullText'
  37. ];
  38. }
  39. }

Using

Call method for getting a search results.
This method return a SearchResult objects in array.

  1. /**
  2. * @var \bl\search\data\SearchResult[] $result
  3. */
  4. $result = Yii::$app->searcher->search('Black lamp');
  5. foreach($result as $res) {
  6. $res->title;
  7. $res->description;
  8. $res->url;
  9. }