What would the magento 2 equivalent of Mage::helper('core')->? - magento2

What would the magento 2 equivalent of Mage::helper('core')-> ?

The Mage static methods are not existing anymore, you will have to use dependency injection to get your helper instance, for example in your model:
<?php
namespace Mycompany\Mymodule\Model;
use Mycompany\Mymodule\Helper\Data;
class Custom {
private $helper;
public function __construct(
Data $helper
) {
$this->helper = $helper;
}
public function myMethod() {
$this->helper->helperMethod();
}
}
You can use the same system in Blocks etc.. and for existing helpers that you want to use.

Related

How to instance doctrine entity manager in a symfony2 class

I am new with Symfony 2 and Doctrine.
I have created a new class on my symfony project, which is located in:
project_folder/src/Libraries/Validarcontenido/Validarcontenido.php
I need to get the Doctrine Entity Manager instance in this class.
I have reading docs about it, and everyone says that i must add the class into the services.yml file, but didn't work.
Here is my code:
<?php
namespace Libraries\Validarcontenido;
use AdminBundle\Entity\Aportes;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Request;
class Validarcontenido
{
private $request, $post, $em;
public function __construct()
{
$this->request = Request::createFromGlobals();
$this->post = $this->request->request->all();
// gets doctrine instance
$this->em = $this->getContainer()->get('doctrine');
}
}
And the services.yml:
# Learn more about services, parameters and containers at
# http://symfony.com/doc/current/book/service_container.html
parameters:
# parameter_name: value
services:
validarcontenido.service:
class: Libraries\Validarcontenido\Validarcontenido
arguments: [#doctrine.orm.entity_manager]
But Symfony returns me this error message:
Attempted to call an undefined method named "getContainer" of class "Libraries\Validarcontenido\Validarcontenido".
500 Internal Server Error - UndefinedMethodException
What i am doing wrong? Thank you so much.
You have to use the constructor to set the entity manager:
class Validarcontenido
{
private $request, $post, $em;
public function __construct(EntityManager $em)
{
$this->request = Request::createFromGlobals();
$this->post = $this->request->request->all();
$this->em = $em;
}
}
You need to create your class as a service in the service.yml as you already did, only you were almost there.
You need to change your class as this:
<?php
namespace Libraries\Validarcontenido;
use AdminBundle\Entity\Aportes;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Request;
class Validarcontenido
{
private $request, $post, $em;
public function __construct(EntityManager $em)
{
$this->request = Request::createFromGlobals();
$this->post = $this->request->request->all();
// gets doctrine instance
$this->em = $em;
}
}
Heres a working example (that provides the container): https://codedump.io/share/tpxgpEMJnaiW
Ok, the problem was that when i create the service instance in the controller i used this:
$my_class = new My_class();
And now i know that i have to use this:
$my_class = $this->get('service_name');
Thank you so much!

Is there a way to use MongoDB without ORM in Laravel 5?

Basically, I see Eloquent (for that matter, any ORM) as overhead, as MongoDB itself deals with document objects.
I am looking to use native PHP MongoDB code with application wide database connection object, for a greater performance.
Any library or a simple way to achieve this?
I have read a few things and used PHP MongoDB driver with custom "Model" code, with base class like below:
AppModel.php
<?php
namespace App;
use MongoClient;
use MongoId;
use Log;
class AppModel {
public $collection;
public function __construct() {
$mongo = new MongoClient();
$model_name = (new \ReflectionClass($this))->getShortName();
$collection_name = str_plural(strtolower($model_name));
$this->collection = $mongo->selectCollection('proj_zabbit', $collection_name);
}
public function findById($id) {
return $this->collection->findOne(array(
'_id' => new MongoId($id)
));
}
// more wrapper functions ..
}
Extended model class:
<?php
namespace App;
class Message extends AppModel {
}
In Controller:
<?php namespace App\Http\Controllers;
use App\Message;
class MessagesController extends Controller {
public function __construct()
{
$this->Message = new Message;
}
public function get()
{
$id = Input::get('id');
$message = $this->Message->findById($id);
return $message;
}
}

Inject Doctrine Entity Manager to Zf2 Form

I tried to inject doctrine entity manager in zf2 form in the way that is described here
http://zf2cheatsheet.com/#doctrine (Inject the Entity Manager to Form) but it fails with error _construct() must be an instance of Doctrine\ORM\EntityManager, null given...
Anybody solved this problem ?
There are a few ways on how to do this. The dirty but easier way is to just give the form In your Controller Action The Entity Manager trough a param like so:
/**
* #var Doctrine\ORM\EntityManager
*/
protected $em;
public function getEntityManager()
{
if (null === $this->em) {
$this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
}
return $this->em;
}
public function setEntityManager(EntityManager $em)
{
$this->em = $em;
}
...
public function yourAction() {
...
$form = new YourForm($this->getEntityManger());
...
}
You then can just call entity Manager methods within your form:
public function __construct($em)
{
...
$repository = $em->getRepository('\Namespace\Entity\Namespace');
...
}
The more complex but nicer way requires you to add the getServiceconfig function within your modules Module.php:
public function getServiceConfig()
{
return array(
'factories' => array(
'YourFormService' => function ($sm) {
$form = new YourForm($sm);
$form->setServiceManager($sm);
return $form;
}
)
);
}
Within your Form you´ll need to implent the ServiceManagerAwareInterface and the setServiceManager setter.
use Zend\Form\Form as BaseForm;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class CategoryForm extends BaseForm implements ServiceManagerAwareInterface
{
protected $sm;
public function setServiceManager(ServiceManager $sm)
{
$this->sm = $sm;
}
public function __construct($sm)
{
...
$em = $sm->get('Doctrine\ORM\EntityManager');
...
}
You then have to call your Form within your controller differently. The usual$form = new YourForm(); constructor will not work with the factory we created.
$form = $this->getServiceLocator()->get('YourFormService');
I usually use the dirty way to get the Entitymanager but as soon as I need the Service Locator I create a factory personally I dont think its worth it to create a big overhead with the services.
I hope this helped a bit.

Initialize a model in Zend Framework

According to this blog post it should be possible to have an init() method within the model. Like this:
class MyModel
{
public function init()
{
// prepare something
}
...
}
This does not work for me. Does anybody know if I have to set somewhere a parameter (e.g. in the config file) or if this is not possible any more in my Zend FW version (1.11.4)? I checked with error_log('something') within the init method and it does not get called at all.
UPDATE:
I have extended Adam's solution a little:
public function __construct() {
if (get_parent_class($this) != false) {
parent::__construct();
}
if(method_exists($this, 'init')) {
$this->init();
}
}
This way it can be placed in a base class and then extended. Just in case someone needs the same solution later too.
That post is very misleading. If the model classes in the application extend Zend_Db_Table or Zend_Db_Table_Row, which is not the case in the post's examples but is implied from the text, then yes you can add an init() method that will be called automatically. For this to work in your application you would need to be calling the method from whatever creates your models, or from the constructor of a base class.
Try adding a call to init() from the constructor as so:
public function __construct()
{
parent::__construct();
$this->init();
}
you have that problem because a php class does not have an init method. That init method is only applicable to Zend classes. Which mean you can only use it when you extend a Zend class. Which means you are actually overriding the init method.
E.g. here it is in the Zend_Db_Table_Abstract class:
/**
* Initialize object
*
* Called from {#link __construct()} as final step of object instantiation.
*
* #return void
*/
public function init()
{
}
So if you change your model to extend zend it will work:
class MyModel extends Zend_Db_Table_Abstract
{
public function init()
{
// prepare something
}
...
}
It's the same with Zend_Controller_Action, which is why you can also use it in your controllers.

Referencing variable set by application in models (a good idea?)

i am using zend framework 1.10 with doctrine 2. i wonder if in my (doctrine) model class, isit a good idea to reference a variable set by my application (bootstrap.php, variable stored in Zend_Registry, i think its something like a global variable)
what i want to access is the doctrine entityManager. also i want the id of the logged in user
I am building a project with similar setup (ZF 1.10 + Doctrine2) and I've used dependency injection to deal with this situation, much like takeshin said. Here goes full project repository URL: https://bitbucket.org/phpfour/zf-doctrine2. Below are some code excerpts.
Here's my controller:
<?php
require_once APPLICATION_PATH . "/models/PostManager.php";
class IndexController extends Zend_Controller_Action
{
private $_em;
public function init()
{
$this->_em = $this->getInvokeArg('bootstrap')->getResource('doctrine');
}
public function indexAction()
{
$pm = new PostManager($this->_em);
$this->view->posts = $pm->getPublicPosts();
}
My entity manager (or service class):
<?php
class PostManager
{
protected $_em;
public function __construct(Doctrine\ORM\EntityManager $em)
{
$this->_em = $em;
}
public function getPublicPosts()
{
$query = $this->_em->createQuery('SELECT p FROM Entities\Post p WHERE p.visible = true');
$posts = $query->getResult();
return $posts;
}
Hope this helps!
you should simply use Zend_Auth for the logged-in-userId problem, then could do something like the following in your model
class Model extends BaseModel
{
public function something()
{
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$loggedInUserId = $auth->getIdentity()->id;
}
}
}
There is nothing wrong with this approach (unless you are referring to singletons). Use dependency injection where possible.
However I'd create a service (or two) for this.
class Modulename_Services_Servicename
{
public function getCurrentUser() { ... }
public function getCurrentUserModel() { ... }
public function isLogged() { ... }
public function authenticate() { ... }
public function getSomeData()
{
$user = $this->getCurrentUser()
$model = new YourModel($user);
$query = ....;
$result = $query->execute();
return $result;
}
public function getSomeMoreData($usermodel) { ... }
}