I have tested symfony3 with both eclipse and netbeans IDE and I still don't manage to get autocompletion...
Here is my controller:
<?php
// src/OC/PlatformBundle/Controller/AdvertController.php
namespace OC\PlatformBundle\Controller;
// N'oubliez pas ce use :
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class AdvertController extends Controller
{
public function indexAction()
{
$content = $this->get('templating')->render('OCPlatformBundle:Advert:index.html.twig');
return new Response($content);
}
}
In Eclipse I can have autocomplete for $this (then I have get as a choice), but I never get the render method with autocompletion..
I looked at this Preserving auto-completion abilities with Symfony2 Dependency Injection but I couldn't get it working.
Can anyone help me with my example please?
Try this:
public function indexAction()
{
/** #var $twig \Symfony\Bundle\TwigBundle\TwigEngine */
$twig = $this->get('templating');
$content = $twig->render('OCPlatformBundle:Advert:index.html.twig');;
return new Response($content);
}
Maybe you need to adjust the comment hint but it should work.
But my advice would be: Get PhpStorm with the symfony Plugin (i know it's not free but give the trial a try and decide if it's worth it)
Related
I am trying to build an extension. In this extension, I'm trying to connect to the database of TYPO3 but I can't access this class and any class is always not found
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
class rpc {
/**
*
* #var string
*/
public $tsc_Endpoint = '';
/**
*
* #var string
*/
public $tsc_tokenID = '';
/**
* The main method of the backend module
*/
public function main(){
$connection = GeneralUtility::makeInstance(
ConnectionPool::class)
->getConnectionForTable('gpi_configurations');
$queryBuilder = $connection->createQueryBuilder();
$query = $queryBuilder
->select('*')
->from('gpi_configurations')
->where('config_name = tsc_Endpoint');
$rows = $query->execute->fetchRows();
print_r($rows);
$client = GeneralUtility::makeInstance(GpiClient::class);
try {
$server = GeneralUtility::makeInstance(JsonRpc::class)->__construct($client);
} catch (\Exception $e) {
}
echo $server->process();
}
}
$q = new rpc();
$q->main();
I want to mention something this bulk of code in a file called rpc.php
Is there a way to access TYPO3 functionality on rpc.php? I did many searches but I did not find any useful help.
installing
structure
Full edit:
From our conversation below, I think what you need is a Middleware to provide an endpoint. This endpoint reads data from the TYPO3-database passes them your your rpc-service and returns some JSON as $response.
To ensure autoloading, all your PHP-code should go into the Classes/ folder.
You have to use namespace Mazen\YourExtensionName\... in your Classes.
I would recommend to make your rpc-class a service and put it into Classes/Service/ but I might not know enough about your application.
Read the Docs about TYPO3 Doctrine, especially the part about the WHERE clause.
Reading and learning some basic priceless about TYPO3 Extension Development might be a good idea.
Middleware
https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/RequestHandling/Index.html
German, but a nice snippet for a Mailchimp endpoint: https://various.at/news/typo3-tipps-und-tricks-psr-15-mideelware-am-beispiel-mailchimp-webhook#c971
Doctrine
https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Database/QueryBuilder/Index.html#where-andwhere-and-orwhere
Services
The Service API it self is deprecated, but you still can group some parts of your application into service ans load them with Dependency Injection from everywhere you need them.
https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/DependencyInjection/Index.html
TYPO3 Extension Development
Developing TYPO3 Extensions: https://docs.typo3.org/m/typo3/book-extbasefluid/master/en-us/Index.html
I'm using Twig view for my slim 3 application but I don't know how to make pagination using the eloquent ORM below is my code.
MODEL:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
protected $table = "todo";
protected $fillable = [
'todo_name',
];
}
and this is my code to render a view
use App\Models\Todo;
$app->get('/', function ($request, $response) {
$data = Todo::all()->paginate(5);
return $this->view->render($response, 'home.twig', [
'title' => 'Home',
'todolist' => $data,
]);
})->setName('homepage');
and I got this error
Method paginate does not exist.
Try $data = Todo::paginate(5);
To use pagination you need illuminate/pagination package. It is not included by default when you include illuminate/database. You can use composer to include it in your project:
composer require illuminate/pagination
And you should not call paginate() method after a call to all() or get(). Try this instead:
$data=Todo::paginate(5);
And please note, for pagination to work correctly, it needs to know current page number otherwise it will always return results for first page. Please have a look at this answer to see how to setup page resolver.
Is there any way to set the circular reference limit in the serializer component of Symfony (not JMSSerializer) with any config or something like that?
I have a REST Application with FOSRestBundle and some Entities that contain other entities which should be serialized too. But I'm running into circular reference errors.
I know how to set it like this:
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getName();
});
But this has to be done in more than one controller (overhead for me).
I want to set it globally in the config (.yml) e.g. like this:
framework:
serializer:
enabled: true
circular_limit: 5
Found no serializer API reference for this so I wonder is it possible or not?
For a week have I been reading Symfony source and trying some tricks to get it work (on my project and without installing a third party bundle: not for that functionality) and I finally got one. I used CompilerPass (https://symfony.com/doc/current/service_container/compiler_passes.html)... Which works in three steps:
1. Define build method in bundle
I choosed AppBundle because it is my first bundle to load in app/AppKernel.php.
src/AppBundle/AppBundle.php
<?php
namespace AppBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AppBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new AppCompilerPass());
}
}
2. Write your custom CompilerPass
Symfony serializers are all under the serializer service. So I just fetched it and added to it a configurator option, in order to catch its instanciation.
src/AppBundle/AppCompilerPass.php
<?php
namespace AppBundle;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class AppCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$container
->getDefinition('serializer')
->setConfigurator([
new Reference(AppConfigurer::class), 'configureNormalizer'
]);
}
}
3. Write your configurer...
Here, you create a class following what you wrote in the custom CompilerPass (I choosed AppConfigurer)... A class with an instance method named after what you choosed in the custom compiler pass (I choosed configureNormalizer).
This method will be called when the symfony internal serializer will be created.
The symfony serializer contains normalizers and decoders and such things as private/protected properties. That is why I used PHP's \Closure::bind method to scope the symfony serializer as $this into my lambda-like function (PHP Closure).
Then a loop through the nomalizers ($this->normalizers) help customize their behaviours. Actually, not all of those nomalizers need circular reference handlers (like DateTimeNormalizer): the reason of the condition there.
src/AppBundle/AppConfigurer.php
<?php
namespace AppBundle;
class AppConfigurer
{
public function configureNormalizer($normalizer)
{
\Closure::bind(function () use (&$normalizer)
{
foreach ($this->normalizers as $normalizer)
if (method_exists($normalizer, 'setCircularReferenceHandler'))
$normalizer->setCircularReferenceHandler(function ($object)
{
return $object->getId();
});
}, $normalizer, $normalizer)();
}
}
Conclusion
As said earlier, I did it for my project since I dind't wanted FOSRestBundle nor any third party bundle as I've seen over Internet as a solution: not for that part (may be for security). My controllers now stand as...
<?php
namespace StoreBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ProductController extends Controller
{
/**
*
* #Route("/products")
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository('StoreBundle:Product')->findAll();
return $this->json(['data' => $data]);
}
/**
*
* #Route("/product")
* #Method("POST")
*
*/
public function newAction()
{
throw new \Exception('Method not yet implemented');
}
/**
*
* #Route("/product/{id}")
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository('StoreBundle:Product')->findById($id);
return $this->json(['data' => $data]);
}
/**
*
* #Route("/product/{id}/update")
* #Method("PUT")
*
*/
public function updateAction($id)
{
throw new \Exception('Method not yet implemented');
}
/**
*
* #Route("/product/{id}/delete")
* #Method("DELETE")
*
*/
public function deleteAction($id)
{
throw new \Exception('Method not yet implemented');
}
}
The only way I've found is to create your own object normalizer to add the circular reference handler.
A minimal working one can be:
<?php
namespace AppBundle\Serializer\Normalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
class AppObjectNormalizer extends ObjectNormalizer
{
public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null)
{
parent::__construct($classMetadataFactory, $nameConverter, $propertyAccessor, $propertyTypeExtractor);
$this->setCircularReferenceHandler(function ($object) {
return $object->getName();
});
}
}
Then declare as a service with a slithly higher priority than the default one (which is -1000):
<service
id="app.serializer.normalizer.object"
class="AppBundle\Serializer\Normalizer\AppObjectNormalizer"
public="false"
parent="serializer.normalizer.object">
<tag name="serializer.normalizer" priority="-500" />
</service>
This normalizer will be used by default everywhere in your project.
I have installed php-di 4.4 in a new custom project using composer.Im runing a xampp localhost with php 5.6.3 but I set netbeans for php 5.4 on this project. Im new to php-di, I did use annotations in my android projects but cant seem to make it work here. The code is simple, im testing out the injection to see how it works, here is the code:
// composer autoload
require_once __DIR__ . '/vendor/autoload.php';
// injection entry point
$builder = new DI\ContainerBuilder();
$container = $builder->build();
class ClassA
{
public function methodA()
{
echo 'methodA';
}
}
class ClassB
{
/**
* #Inject
* #var ClassA
*/
public $param;
public function methodB()
{
$this->param->methodA();
}
}
$b = new ClassB();
$b->methodB();
this is the error that i get:
Call to a member function methodA() on null in D:\Projects\profi\test.php on line 27
It's basic implementation I don't understand why it does not inject.
Thank you in advance.
PHP-DI cannot magically intercept when you create B (to inject A in B). You have to create B using PHP-DI:
$b = $container->get('ClassB');
$b->methodB();
What is a Zend View Filter? I see them mentioned in the ZF1 documentation, http://framework.zend.com/manual/1.12/en/zend.view.introduction.html, and in the Zend_View code, but I can't find an explanation for them.
Perhaps it is to support other templating systems which have filters? In that case, what do the filters do in these templating systems?
Thanks!
here is an example of a Zend View Filter:
http://dev.bigace.org/api/3.0/Bigace_Zend/View_Filter/Bigace_Zend_View_Filter_ObfuscateMailto.html
It filters found mailto links and obfuscates them.
A Zend View Filter does something on an already rendered phtml file (= html code) before it is send to the client.
It's a Zend_Filter that can be used on the Zend View output.
Here is another example with code from:
http://www.phpgangsta.de/zend_view-output-filter-whitespaces-aus-html-entfernen
The filter class (filters whitespaces from html = less code to send):
<?php
class App_View_Filter_Minify implements Zend_Filter_Interface
{
public function filter($string)
{
return preg_replace(
array('/>\s+/', '/\s+</', '/[\r\n]+/'),
array('>', '<', ' '),
$string
);
}
}
And then adding the filter to the view:
/**
* Add Output filters to View
*
* #return void
*/
protected function _initViewFilter()
{
$view = $this->getResource('view');
$view->addFilterPath('App/View/Filter', 'App_View_Filter_')
->addFilter('Minify');
}