PHP code example of baraja-core / doctrine-fulltext-search

1. Go to this page and download the library: Download baraja-core/doctrine-fulltext-search library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

baraja-core / doctrine-fulltext-search example snippets


use Baraja\Search\Search;
use Doctrine\ORM\EntityManagerInterface;

$search = new Search($entityManager);

$search = new Search(
    em: $entityManager,
    queryNormalizer: new CustomQueryNormalizer(),
    scoreCalculator: new CustomScoreCalculator(),
);

$results = $search->search($query, [
    Article::class => [':title', 'description', 'content'],
    User::class => ':username',
    Product::class => [':name', 'sku', '!internalCode'],
]);

echo $results; // Uses built-in HTML renderer

$results = $search->selectorBuilder($query)
    ->addEntity(Article::class)
        ->addColumnTitle('title')
        ->addColumn('description')
        ->addColumn('content')
    ->addEntity(User::class)
        ->addColumnTitle('username')
        ->addEntity(Product::class)
        ->addColumnTitle('name')
        ->addColumn('sku')
        ->addColumnSearchOnly('internalCode')
    ->search();

$results = $search->selectorBuilder($query)
    ->addEntity(Article::class)
        ->addColumnTitle('title')
        ->addColumn('content')
    ->addWhere('active = TRUE')
    ->addWhere('publishedAt <= NOW()')
    ->search();

$entityMap = [
    Article::class => [
        ':title',           // Title column - always shown
        'description',      // Normal - searched and in snippet
        '!slug',            // Search only - searched but not in snippet
        '_authorId',        // Select only - loaded but not searched
    ],
];

$search->selectorBuilder($query)
    ->addEntity(Article::class)
        ->addColumnTitle('title')           // :title
        ->addColumn('description')          // description
        ->addColumnSearchOnly('slug')       // !slug
        ->addColumnSelectOnly('authorId')   // _authorId
    ->search();

$entityMap = [
    Article::class => [
        ':title',
        'author.name',           // ManyToOne: Article -> Author
        'categories.name',       // ManyToMany: Article -> Categories
        'content.versions.text', // Deep relation chain
    ],
];

$entityMap = [
    Article::class => [
        'versions(content)', // Joins 'versions' but calls getContent()
    ],
];

$query = '"to be or not to be"';
// Finds exact phrase

$query = 'linux -ubuntu';
// Finds "linux" but excludes results containing "ubuntu"

$query = 'conference 2020..2024';
// Finds results containing years 2020, 2021, 2022, 2023, or 2024

$results = $search->search($query, $entityMap);

// Total count
$count = $results->getCountResults();

// Search time in milliseconds
$time = $results->getSearchTime();

// "Did you mean?" suggestion
$suggestion = $results->getDidYouMean();

// Iterate results
foreach ($results as $item) {
    echo $item->getTitle();
}

// Get first 10 results
$items = $results->getItems();

// With pagination
$items = $results->getItems(limit: 20, offset: 40);

// Filter by entity type
$articles = $results->getItemsOfType(Article::class, limit: 10);

// Get only IDs
$ids = $results->getIds(limit: 100);

echo $results;

$results = $search->search('programing', $entityMap);

if ($results->getCountResults() === 0) {
    $suggestion = $results->getDidYouMean();
    if ($suggestion !== null) {
        echo "Did you mean: $suggestion?"; // "programming"
    }
}

$results = $search->search($query, $entityMap, useAnalytics: false);

// Or with SelectorBuilder
$results = $search->selectorBuilder($query)
    ->addEntity(Article::class)
        ->addColumnTitle('title')
    ->search(useAnalytics: false);

use Baraja\Search\ScoreCalculator\IScoreCalculator;

class CustomScoreCalculator implements IScoreCalculator
{
    public function process(string $haystack, string $query, string $mode = null): int
    {
        // Your custom scoring logic
        return $score;
    }
}

use Baraja\Search\QueryNormalizer\IQueryNormalizer;

class CustomQueryNormalizer implements IQueryNormalizer
{
    public function normalize(string $query): string
    {
        // Your normalization logic
        return $normalizedQuery;
    }
}

$container = new Container(
    entityManager: $em,
    searchTimeout: 5000, // 5 seconds
);

$search = new Search($em, container: $container);

$results = $search->search(
    query: $query,
    entityMap: $entityMap,
    searchExactly: true,
);

$results = $search->search(
    query: $query,
    entityMap: $entityMap,
    userConditions: [
        'e.active = TRUE',
        'e.deletedAt IS NULL',
    ],
);

use Baraja\Search\Helpers;

$highlighted = Helpers::highlightFoundWords(
    haystack: $text,
    words: $query,
    replacePattern: '<mark>\0</mark>',
);